FileInputStream (file) returning ENOENT (no such file or directory) android
I am trying to extract a file (any type) from a file manager and encode that file to String Base64. I found many answers related to IMAGES, but I need any type of file. He is what I do.
I am pulling a file (any type) from a gallery like this
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose file"), GALLERY_REQUEST_CODE);
And in my result
Uri returnUri = intent.getData();
Which gives me the content: //com.android.providers.downloads.documents/document/1646 '
Then i try
File file = new File( returnUri.getPath() );
So far so good, but then I try to encode the file to Base64 string:
String str = null;
try {
str = convertFile(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And the convertFile method
public String convertFile(File file)
throws IOException {
byte[] bytes = loadFile(file);
byte[] encoded = Base64.encode(bytes, Base64.DEFAULT);
String encodedString = new String(encoded);
return encodedString;
}
And the loadFile method
private static byte[] loadFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.i("MobileReport","Anexo -> loadfile(): File is too big!");
// File is too large
}
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("It was not possible to read the entire file "+file.getName());
}
is.close();
return bytes;
}
Error in the first line of the loadFile method
InputStream is = new FileInputStream(file);
The app crashes and in the log I got:
java.io.FileNotFoundException: /document/1646: open failed: ENOENT (No such file or directory)
I declared READ and WRITE permissions. Can anyone help me with this error? Thank!
+3
source to share