Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileInputStream(file) returning ENOENT (No such file or directory) android

I'm trying to retrieve a file (any type) from file manager and encode this file in a Base64 String. I've found a lot of answers involving IMAGES, but I need any type of file. He's what I'm doing.

I'm retrieving a file(any type) from 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();

What gives me '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 into a 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;
}

The error is in the first line of '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've declared the READ and WRITE permissions. Could anyone help me with that error? Thank you!

like image 448
Heitor Colangelo Avatar asked Nov 01 '22 11:11

Heitor Colangelo


1 Answers

returnUri is a Uri. It is not a filesystem path.

In particular, if you examine it, you will find that it is a content:// Uri. To get an InputStream for that content, use openInputStream() on a ContentResolver.

like image 153
CommonsWare Avatar answered Nov 04 '22 08:11

CommonsWare