获取Uri对任何类型文件的真实路径

时间:2018-02-09 12:43:23

标签: android

以下是我想在我的应用中执行的操作:

  • 允许用户在数据库中选择文件并存储它们的路径
  • 显示这些文件的名称
  • 允许用户点击文件名并打开所选文件

所以我想获得存档和存储的真实路径。只允许用户从内部/外部存储器获取文件,因此,正如我所假设的那样,实际路径将始终存在。我一直在寻找解决方案,几乎所有人都只询问图像/音频/视频,并在他们的解决方案中使用MediaStore(而且,我现在不知道这是什么,我可以在不使用它的情况下获得Uri)。我想要一个适用于任何类型文件的解决方案,如果可能的话。

以下是我如何获得Uri:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Choose File"), 1);

我将收到的信息存储在onActivityResult方法中。

所以我得到Uri并将其存储为一个字符串,例如content://com.android.providers.downloads.documents/document/4588。如何将其转换为真正的文件路径?

2 个答案:

答案 0 :(得分:1)

从我的某个项目中共享我的Fileutils文件

public class FileUtils {

public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context
            .getApplicationContext(), uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[]{
                    split[1]
            };
        } else if (isGoogleDriveFile(uri)) {
            String mimeType = context.getContentResolver().getType(uri);
            Cursor returnCursor =
                    context.getContentResolver().query(uri, null, null, null, null);
            int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
            returnCursor.moveToFirst();
            String fileName = returnCursor.getString(nameIndex);
            Log.d("name", returnCursor.getString(nameIndex));
            Log.d("size", Long.toString(returnCursor.getLong(sizeIndex)));
            try {
                InputStream inputStream = context.getContentResolver().openInputStream(uri);

                File root = new File(Environment.getExternalStorageDirectory(), "WittyParrot");
                root.mkdirs();
                File file = new File(root, fileName);
                copyStreamToFile(file, inputStream);
                return Uri.fromFile(file).getPath();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                returnCursor.close();

            }

        }
    }

    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = {
                MediaStore.Images.Media.DATA
        };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver()
                    .query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

public static boolean isGoogleDriveFile(Uri uri) {
    return "com.google.android.apps.docs.storage".equals(uri.getAuthority());
}

public static void copyStreamToFile(File file, InputStream input) {
    try {
        OutputStream output = new FileOutputStream(file);
        try {
            byte[] buffer = new byte[4 * 1024]; // or other buffer size
            int read;

            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }

            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            output.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

答案 1 :(得分:0)

  

只允许用户从内部/外部存储中获取文件

不符合你的代码。用户可以使用支持ACTION_GET_CONTENT的任何内容。不要求ACTION_GET_CONTENT实施仅限于外部存储,也不能使用文件系统从其他应用访问internal storage

如果您只愿意使用external storage,请使用a file chooser library,而不是ACTION_GET_CONTENTACTION_OPEN_DOCUMENT

  

我想要一个适用于任何类型文件的解决方案,如果可能的话。

使用a file chooser library

  

如何将其转换为真正的文件路径?

You don't

相关问题