我正在尝试从文件管理器中检索文件(任何类型),并将该文件编码为Base64字符串。
我找到了很多有关IMAGES的答案,但我需要任何类型的文件。
他就是我在做什么。

我正在从像这样的画廊中检索文件(任何类型)

Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose file"), GALLERY_REQUEST_CODE);

而我的结果
Uri returnUri = intent.getData();

是什么让我'content://com.android.providers.downloads.documents/document/1646'

然后我尝试
File file = new File( returnUri.getPath() );

到目前为止一切顺利,但随后我尝试将文件编码为Base64字符串:
    String str = null;
    try {
        str = convertFile(file);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

和convertFile方法
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;

}

和loadFile方法
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;
}

错误在“loadFile”方法的第一行
InputStream is = new FileInputStream(file);

该应用程序崩溃了,并且在日志中我得到了:
java.io.FileNotFoundException: /document/1646: open failed: ENOENT (No such file or directory)

我已经声明了READ和WRITE权限。
有人可以帮我解决这个错误吗?
谢谢!

最佳答案

returnUriUri。它不是文件系统路径。

特别地,如果您检查它,您会发现它是content:// Uri。要获取该内容的InputStream,请在openInputStream()上使用ContentResolver

07-28 02:19
查看更多