java uri 文件路径_如何通过文件路径从MediaStore获取Uri?

您还可以以更通用的方式对MediaStore中的任何内容执行此操作 . 我必须从URI获取路径并从路径获取URI . 前者:

/**

* Gets the corresponding path to a file from the given content:// URI

* @param selectedVideoUri The content:// URI to find the file path from

* @param contentResolver The content resolver to use to perform the query.

* @return the file path as a string

*/

private String getFilePathFromContentUri(Uri selectedVideoUri,

ContentResolver contentResolver) {

String filePath;

String[] filePathColumn = {MediaColumns.DATA};

Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);

cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

filePath = cursor.getString(columnIndex);

cursor.close();

return filePath;

}

后者(我为视频做的,但也可以通过将MediaStore.Audio(等)替换为MediaStore.Video来用于音频或文件或其他类型的存储内容:

/**

* Gets the MediaStore video ID of a given file on external storage

* @param filePath The path (on external storage) of the file to resolve the ID of

* @param contentResolver The content resolver to use to perform the query.

* @return the video ID as a long

*/

private long getVideoIdFromFilePath(String filePath,

ContentResolver contentResolver) {

long videoId;

Log.d(TAG,"Loading file " + filePath);

// This returns us content://media/external/videos/media (or something like that)

// I pass in "external" because that's the MediaStore's name for the external

// storage on my device (the other possibility is "internal")

Uri videosUri = MediaStore.Video.Media.getContentUri("external");

Log.d(TAG,"videosUri = " + videosUri.toString());

String[] projection = {MediaStore.Video.VideoColumns._ID};

// TODO This will break if we have no matching item in the MediaStore.

Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);

cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(projection[0]);

videoId = cursor.getLong(columnIndex);

Log.d(TAG,"Video ID is " + videoId);

cursor.close();

return videoId;

}

基本上, MediaStore 的 DATA 列(或您查询的任何子部分)都存储文件路径,因此您可以使用该信息进行查找 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值