首页 文章

如何从URI获取文件路径? [重复]

提问于
浏览
36

这个问题在这里已有答案:

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

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

The correct path is

/sdcard/my Report.pdf

Please note 我在stackoverflow上搜索但是找到了获取图像或视频的文件路径的示例, there is no example of how to get the filepath in case of PDF

My code , NOT all the code but only the pdf part

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获取正确的路径?

2 回答

  • 21
    File myFile = new File(uri.toString());
    myFile.getAbsolutePath()
    

    应该返回正确的路径

    EDIT

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

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

    以下是问题的答案here

    实际上我们必须从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;
    

    }

相关问题