Android文件选择器无法返回正确URI,如何获取真实文件路径?
Android 从Content Uri获取真实文件路径(最近文件栏选中文件适配)
问题本质
从最近文件栏选中文件时返回的content://com.android.providers.media.documents/document/xxx是媒体库文档Uri,这类Uri并非直接指向文件系统路径,而是Android存储访问框架(SAF)提供的间接访问标识,需要通过ContentResolver查询MediaStore数据库来获取真实路径。
解决方案步骤
1. 解析Uri提取文档ID
先从Uri中解码并提取核心文档ID:
// 示例Uri: content://com.android.providers.media.documents/document/document%3A1000007352 String documentId = DocumentsContract.getDocumentId(uri); // 分割出数字ID部分,解码后格式为 "document:1000007352" String id = documentId.split(":")[1];
2. 查询MediaStore获取真实路径
通过ContentResolver查询MediaStore中匹配ID的记录,提取DATA列的值即为真实文件路径:
public String getRealPathFromContentUri(Context context, Uri uri) { String documentId = DocumentsContract.getDocumentId(uri); String id = documentId.split(":")[1]; String[] projection = {MediaStore.Files.FileColumns.DATA}; String selection = MediaStore.Files.FileColumns._ID + "=?"; String[] selectionArgs = {id}; Cursor cursor = context.getContentResolver().query( MediaStore.Files.getContentUri("external"), projection, selection, selectionArgs, null ); String realPath = null; if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(projection[0]); realPath = cursor.getString(columnIndex); cursor.close(); } return realPath; }
3. 细分文件类型适配(可选)
如果需要针对图片、视频等特定类型优化,可以根据Uri前缀选择对应MediaStore表:
- 图片:
MediaStore.Images.Media.EXTERNAL_CONTENT_URI - 视频:
MediaStore.Video.Media.EXTERNAL_CONTENT_URI - 音频:
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
关键注意事项
- Android 10+ 分区存储适配:Android 10及以上启用了分区存储,直接获取真实路径可能受限。如果仅需读取文件内容,建议直接通过
ContentResolver.openInputStream(uri)获取输入流操作,无需依赖真实路径。 - 权限说明:Android 9及以下需申请
READ_EXTERNAL_STORAGE权限;Android 10+通过SAF选择文件时,已自动获得临时访问权限,无需额外申请。 - 云端文件处理:部分最近文件栏的文件来自云端(如Google Drive),不存在本地真实路径,此时需提示用户选择本地文件,或直接通过Uri操作文件。
内容的提问来源于stack exchange,提问作者Swapnil33
相关产品推荐
相关产品推荐

