【问题标题】:Android correct way to get File from UriAndroid从Uri获取文件的正确方法
【发布时间】:2018-12-14 22:23:17
【问题描述】:

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

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

并管理结果:

    @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 {...}

文件似乎没有成功创建。 我的日志结果是:

  • mylog1 -> content://media/external/file/7406
  • mylog2 -> /external/file/7406
  • mylog3 -> /external/file/7406
  • mylog4 -> /external/file/7406
  • mylog5 -> 错误

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

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

...
InputStream inputStream = new FileInputStream(file);
...

但是我看到我的应用在 Logcat 中崩溃了:

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

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

【问题讨论】:

  • 试试这个` Intent intentPDF = new Intent(Intent.ACTION_GET_CONTENT); intentPDF.setType("应用程序/pdf"); intentPDF.addCategory(Intent.CATEGORY_OPENABLE);`
  • Uri.getPath() 不会为您提供文件系统路径。此外,没有正确的方法可以从这样的 uri 中获取文件。您尝试这样做的方式完全错误。
  • document/raw:/storage/emulated/0/Download/20180702_121938.pdf 这不是一个有效的路径。试试/storage/emulated/0/Download/20180702_121938.pdf
  • @greenapps 使用您的建议我解决了使用子字符串删除 'document/raw:' 的问题:uri.getPath().replace("document/raw:","")。有用。无论如何,这只是一种解决方法。正如你所说“你完全走错了路。”那么,从 onActivityResult 获取文件的正确方法是什么?
  • 对不起,但我明白你为什么说“你不需要文件”。 onActivityResult 只返回一个 Uri。我需要一个 File 对象来执行我的操作...

标签: android file pdf path uri


【解决方案1】:

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

if(mypath.contains("document/raw:")){
    mypath = mypath.replace("/document/raw:","");
}

【讨论】:

  • 经过 3 小时的调试和搜索,您救了我。
猜你喜欢
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多