file picker throwing ENOENT no such file or directory - android

i am trying to pick an audio file and save it , but i am getting ENOENT , yet i use the same code with image and it works fine !!!!! \n
i am using file provider to create/save files and it works more than probably .
how can the same code work with images yet not with audio : \n
here is some code examples \n
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == RESULT_OK) {
Uri resultUri = data.getData();
saveFile(resultUri);
}
}
and to save the file i use :
File dirPath = new File(Environment.getExternalStorageDirectory(),"Moch/WAR/");
File file = new File(dirPath, "notification.mp3");
String sourceFilename = resultUri.getPath();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
if(!file.exists())
if (!file.createNewFile())
Toast.makeText(notificationsSettings.this,"Unable to make sound File",Toast.LENGTH_LONG).show();
if(file.exists()) {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(file, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
mProgressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and this is the doomed error line : \n
/document/audio:266: open failed: ENOENT (No such file or directory)

Related

Failed in converting File path to byte array android [duplicate]

This question already has an answer here:
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 4 years ago.
I'm trying to convert a File to byte array format. The selected actual path is there in the storage, but still its throwing exception as "File Not Found". Can anyone help me to sort out this?
Thanks for your precious time!..
calling file manager
btn_click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
});
getting response
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String filePath = data.getData().getPath();
System.out.println("====== path : "+filePath);
File file = new File(filePath);
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
System.out.println("====== bytesArray "+bytesArray);
} catch (FileNotFoundException e) {
System.out.println("====== File Not Found.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("====== Error Reading The File. IOException");
e.printStackTrace();
}
}
}
}
Add the following grade its Apache commons gradle
compile 'org.apache.commons:commons-io:1.3.2'
then use this code
byteArray = FileUtils.readFileToByteArray(file);

How to read file contents?

I am trying below code to select pdf from directory and read its contents but its not working
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, PICKFILE_RESULT_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode) {
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
// String filePath = data.getData().getPath();
// textViewFilePath.setText("File : " + filePath);
// readFromPdf(filePath);
StringBuilder text = new StringBuilder();
String filePath = data.getDataString();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('n');
}
scanResults.setText(text + ".....");
}
catch (IOException e) {
//You'll need to add proper error handling here
e.printStackTrace();
}
}
break;
}
}
I am getting below exception
java.io.FileNotFoundException:
content:/com.android.providers.downloads.documents/document/2295: open
failed: ENOENT (No such file or directory)
You should open an InputStream like
InputStream is = getContentResolver().openInputStream(data.getData());
You should not try to use a reader or try to read lines.
Those do not make sense for a pdf file.

How to convert file to base64 in Android?

I have enabled the user to select a specific file from his device the extension of the file is .txt , and I'm using MaterialFilePicker library for it , now how to convert this file to string base64 so I can send the file to the server.
if there's another library or another way to do it please recommend me to use it.
this the code I tried but it didn't work out , thanks.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openFilePicker();
} else {
showError();
}
}
}
}
// FILE PICKER
private void checkPermissionsAndOpenFilePicker() {
String permission = Manifest.permission.READ_EXTERNAL_STORAGE;
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
showError();
} else {
ActivityCompat.requestPermissions(this, new String[]{permission}, PERMISSIONS_REQUEST_CODE);
}
} else {
openFilePicker();
}
}
private void showError() {
Toast.makeText(this, "Allow external storage reading", Toast.LENGTH_SHORT).show();
}
private void openFilePicker() {
new MaterialFilePicker()
.withActivity(this)
.withRequestCode(FILE_PICKER_REQUEST_CODE)
.withHiddenFiles(true)
.withTitle("Sample title")
.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
String path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
if (path != null) {
Log.d("Path: ", path);
file = new File(path);
fileStr = String.valueOf(file);
Toast.makeText(this, "Picked file: " + file, Toast.LENGTH_LONG).show();
}
}
}
//convert the file path to base64
public static String encodeImage(String path) {
File imagefile = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
if (fis != null) {
try {
fis.close();
if (baos != null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Base64.de
return encImage;
}
First read the file to a byte array, and then use
Base64.encodeToString(byte[], int)
to convert it to a Base64 string.
Try this:
File file = new File("myfile.txt");
//convert file to byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(file);
bos.close();
oos.close();
byte[] bytearray = bos.toByteArray();
//convert byte[] to file
ByteArrayInputStream bis = new ByteArrayInputStream(bytearray);
ObjectInputStream ois = new ObjectInputStream(bis);
File fileFromBytes = null;
fileFromBytes = (File) ois.readObject();
bis.close();
ois.close();
System.out.println(fileFromBytes);
Note: Don't forget to handle the exception(try/catch)

how to copy directory (folder) to usb storage

i am trying to copy whole directory to usb storage :
File Sdfile = new File(Environment.getExternalStorageDirectory(), "myfolder");
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.setType("*/*");
intent.setType(DocumentsContract.Document.MIME_TYPE_DIR);//For API 19+
intent.putExtra(Intent.EXTRA_TITLE, Sdfile.getName());
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 47);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 47) {
if (resultCode != RESULT_OK) return;
File file = new File(Environment.getExternalStorageDirectory(), "myfolder");
copyFile(file, data.getData());
}
Below code is for copy the whole folder to usb storage.
private void copyFile(File src, Uri destUri) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));
byte[] buf = new byte[5024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
when i am trying to copy the whole folder then it gives error.
Even i direct copy the whole folder to usb storage .
How can i copy whole directory ?
I'm guessing your app does not have the correct permissions. For Android versions below KitKat, you need to declare the permission WRITE_EXTERNAL_STORAGE in your AndroidManifest.xml
<user-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Reference: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

How to select an audio file and upload it to parse in android

I opened the music player to select an audio file using this code
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload,1);
}
});
I called the uploadAudioToParse method inside OnActivityResult()
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
File abc=new File(uri.toString());
ParseObject ob=new ParseObject("songs");
uploadAudioToParse(abc,ob,"song");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
And this is my uploadAudioToParse method.
private ParseObject uploadAudioToParse(File audioFile, ParseObject po, String columnName){
if(audioFile != null){
Log.d("EB", "audioFile is not NULL: " + audioFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(audioFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
assert in != null;
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] audioBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(audioFile.getName() , audioBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
is the file conversion method correct?

Categories

Resources