如何从URI获取文件路径?

Yaq*_*mad 36 pdf android uri filepath

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

/file:///mnt/sdcard/my%20Report.pdf/my Report.pdf
Run Code Online (Sandbox Code Playgroud)

正确的道路是:

/sdcard/my Report.pdf
Run Code Online (Sandbox Code Playgroud)

请注意我在stackoverflow上搜索但是找到了获取图像或视频的filePath的示例,在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");   
             }               
          }
      }
 }
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我如何从URI获取正确的路径?

Ses*_*nay 21

File myFile = new File(uri.toString());
myFile.getAbsolutePath()
Run Code Online (Sandbox Code Playgroud)

应该返回正确的路径

编辑

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

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你的帮助,但它不起作用.我尝试了getAbsolutePath()和getPath(),但它没有返回正确的路径.你可以尝试一下,你会看到结果. (10认同)
  • 我这里没有FILE,我需要从Uri获得它. (3认同)
  • 要更正此用法:**文件myFile = new File(uri.getPath());** - 适用于file:// ... URIs. (3认同)
  • 不工作 在API 23上测试 (2认同)

she*_*tal 5

这是这里问题的答案

实际上,我们必须从Camera Application的可共享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;
Run Code Online (Sandbox Code Playgroud)

}