【问题标题】:How to get the file path from URI? [duplicate]如何从 URI 中获取文件路径? [复制]
【发布时间】:2012-02-11 16:49:08
【问题描述】:

请在下面找到我的代码。我需要获取用户从 SDcard 中选择的 pdf 文档的文件路径。问题是 URI.getPath() 返回:

/file:///mnt/sdcard/my%20Report.pdf/my Report.pdf

正确的路径是

/sdcard/my Report.pdf

请注意我在stackoverflow上搜索但找到了获取图像或视频文件路径的示例,没有如何获取PDF的文件路径示例?

我的代码,不是所有代码,只有 pdf 部分

 public void openPDF(View v)
 {
     Intent intent = new Intent();
     //intent.setType("pdf/*");
     intent.setType("application/pdf");
     intent.setAction(Intent.ACTION_GET_CONTENT);
     startActivityForResult(Intent.createChooser(intent, "Select Pdf"), SELECT_PDF_DIALOG);
 }
 public void onActivityResult(int requestCode, int resultCode, Intent result) 
 {
     if (resultCode == RESULT_OK) 
     {
         if (requestCode == SELECT_PDF_DIALOG) 
         {
             Uri data = result.getData();
             if(data.getLastPathSegment().endsWith("pdf"))
             {
                String pdfPath = data.getPath();
             } 
             else 
             {
                 CommonMethods.ShowMessageBox(CraneTrackActivity.this, "Invalid file type");   
             }               
          }
      }
 }

能否请教我如何从 URI 中获取正确的路径?

【问题讨论】:

标签: android pdf uri filepath


【解决方案1】:
File myFile = new File(uri.toString());
myFile.getAbsolutePath()

应该返回正确的路径

编辑

正如@Tron 建议的那样,工作代码是

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

【讨论】:

  • 我这里没有文件,我需要从 Uri 获取它。
  • 非常感谢您的帮助,但它不起作用。我尝试了 getAbsolutePath() 和 getPath(),但它没有返回正确的路径。你可以试试,你会看到结果。
  • @Seshu Vinay anwser 是错误的。文件无法创建以方案字符串file:// 开头的对象。 @Yaqub Ahmad 在 uri.getPath 字符串之后使用 URLDecoder.decode
  • 纠正这种用法:File myFile = new File(uri.getPath()); - 适用于 file://... URI。
  • 不工作。 API 23 测试
【解决方案2】:

这是问题的答案 here

其实我们得从Camera Application的shareable ContentProvider中获取。

编辑。复制对我有用的答案

private String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}

【讨论】:

  • 这是为我的物理设备获取“真实”文件路径的唯一方法。我不知道为什么,但我的设备和我的模拟器以不同的方式工作。
  • MediaStore.Images.Media.DATA 已弃用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多