Android从Uri获取文件的正确方法

Fed*_*dro 4 pdf android uri file path

我使用以下方法从本地存档中选择 PDF:

startActivityForResult(Intent.createChooser(new Intent().setType("application/pdf").setAction(Intent.ACTION_GET_CONTENT), getString(R.string.str_select_file)), request_id_archive);
Run Code Online (Sandbox Code Playgroud)

并管理结果:

    @Override
    protected void onActivityResult(int request_code, int result_code, Intent data) {
        super.onActivityResult(request_code, result_code, data);

        if (request_code == request_id_archive && result_code == RESULT_OK && data != null && data.getData() != null) {
            Uri myuri = data.getData();
            String mypath = myuri.getPath();
            File myfile = new File(mypath);
            Log.d("mylog1", uri.toString());
            Log.d("mylog2", uri.getPath());
            Log.d("mylog3", f.getPath());
            Log.d("mylog4", f.toString());
            Log.d("mylog5", Boolean.toString(f.exists()));
        }
        else {...}
Run Code Online (Sandbox Code Playgroud)

看来该文件没有成功创建。我的日志结果是:

  • mylog1 -> 内容://media/external/file/7406
  • mylog2 -> /外部/文件/7406
  • mylog3 -> /外部/文件/7406
  • mylog4 -> /外部/文件/7406
  • mylog5 -> 假

方法 file.exist() 返回该文件不存在。为什么?

在其他代码中,我尝试管理文件以进行许多其他操作:

...
InputStream inputStream = new FileInputStream(file);
...
Run Code Online (Sandbox Code Playgroud)

但我的应用程序在 Logcat 中崩溃了,我看到:

java.io.FileNotFoundException: /document/raw:/storage/emulated/0/Download/20180702_121938.pdf (No such file or directory)
Run Code Online (Sandbox Code Playgroud)

我正在 Android 7 上测试我的代码。

小智 5

您需要将'document/raw'替换为空字符串,因此您需要在访问文件之前添加以下代码:

if(mypath.contains("document/raw:")){
    mypath = mypath.replace("/document/raw:","");
}
Run Code Online (Sandbox Code Playgroud)