如何获取文件的绝对路径?

时间:2016-04-02 10:58:58

标签: android

我想获取从文件选择器中选择的文件的绝对路径 我的OnActivityesult()如下所示:

 if(resultCode == RESULT_OK) {
        switch(requestCode) {
            case 1:
                Uri pathUri = data.getData();
                File userFile = new File(pathUri.getPath());
                IMG_PATH = userFile.getParentFile().getAbsolutePath();
                Snackbar.make(getCurrentFocus(), IMG_PATH, Snackbar.LENGTH_SHORT).show();
                ShowConfirmation(IMG_PATH);
                break;
        }
    }

但此代码返回/document/primary:miniclipId.txt 我需要像mnt/sdcard1/miniclipId.txt这样的真实路径 用户将从SD卡或内部选择.img文件 任何人都可以告诉我如何获得这样的路径字符串?

3 个答案:

答案 0 :(得分:2)

  

但这段代码像/document/primary:miniclipId.t​​xt一样。

您从Uri收到了ContentProvider

  

我需要像mnt / sdcard1 / miniclipId.t​​xt这样的真实路径。

Uri不是文件。没有要求存在真正的路径",更不用说对您有意义的路径了。

使用ContentResolveropenInputStream()consume the content pointed to by the Uri等方法。

如果您确实需要文件,请使用openInputStream()并将内容复制到您控制的某个文件中。

答案 1 :(得分:0)

你可以使用这个函数来获取media.u的真实路径。只需要传递你在onActivityResult()方法中的uri

 public String mf_szGetRealPathFromURI(final Uri ac_Uri) {
    String result = "";
    boolean isok = false;
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(ac_Uri, proj,
                null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
        isok = true;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return isok ? result : "";
}

答案 2 :(得分:0)

这就是我多年来一直使用的

D