android file content,Android: Getting a file URI from a content URI?

If you have a content Uri with content://com.externalstorage... you can use this method to get absolute path of a folder or file on Android 19 or above.

public static String getPath(final Context context, final Uri uri) {

final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

// DocumentProvider

if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

System.out.println("getPath() uri: " + uri.toString());

System.out.println("getPath() uri authority: " + uri.getAuthority());

System.out.println("getPath() uri path: " + uri.getPath());

// ExternalStorageProvider

if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {

final String docId = DocumentsContract.getDocumentId(uri);

final String[] split = docId.split(":");

final String type = split[0];

System.out.println("getPath() docId: " + docId + ", split: " + split.length + ", type: " + type);

// This is for checking Main Memory

if ("primary".equalsIgnoreCase(type)) {

if (split.length > 1) {

return Environment.getExternalStorageDirectory() + "/" + split[1] + "/";

} else {

return Environment.getExternalStorageDirectory() + "/";

}

// This is for checking SD Card

} else {

return "storage" + "/" + docId.replace(":", "/");

}

}

}

return null;

}

You can check each part of Uri using println. Returned values for my SD card and device main memory are listed below. You can access and delete if file is on memory, but I wasn't able to delete file from SD card using this method, only read or opened image using this absolute path. If you find a solution to delete using this method, please share.

SD CARD

getPath() uri: content://com.android.externalstorage.documents/tree/612E-B7BF%3A/document/612E-B7BF%3A

getPath() uri authority: com.android.externalstorage.documents

getPath() uri path: /tree/612E-B7BF:/document/612E-B7BF:

getPath() docId: 612E-B7BF:, split: 1, type: 612E-B7BF

MAIN MEMORY

getPath() uri: content://com.android.externalstorage.documents/tree/primary%3A/document/primary%3A

getPath() uri authority: com.android.externalstorage.documents

getPath() uri path: /tree/primary:/document/primary:

getPath() docId: primary:, split: 1, type: primary

If you wish to get Uri with file:/// after getting path use

DocumentFile documentFile = DocumentFile.fromFile(new File(path));

documentFile.getUri() // will return a Uri with file Uri

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值