我的应用下载并解压缩特定文件夹中的文件:
output = new FileOutputStream(realpath, true);
output.write(buffer, 0, bytesRead);
ZipFile zipFile = new ZipFile(realpath);
使用新引入的ACTION_OPEN_DOCUMENT_TREE
Intent,我想让用户选择该文件夹。
在测试我的onActivityResult
中收到的值时,我会得到类似/tree/primary:mynewfolder
的路径,这不是像/sdcard/mynewfolder
这样的物理真实路径。
Uri treeUri = data.getData();
String sPath = treeUri.getPath();
Log.v("Path from Tree ", sPath);
我的解压方法需要真正的路径:
ZipFile zipFile = new ZipFile(realpath);
如何从Lollipop(API 21& 22)中提供的URI获取/sdcard/mynewfolder
这样的真实路径?
答案 0 :(得分:11)
从URI获取真实路径的过程与之前相同,但稍加一点:
Uri uri = data.getData();
Uri docUri = DocumentsContract.buildDocumentUriUsingTree(uri,
DocumentsContract.getTreeDocumentId(uri));
String path = getPath(this, docUri);
可以在此处找到带有中间方法的getPath()方法的要点:getPath()
答案 1 :(得分:0)
无需检查安卓版本..
public static string GetRealPath(DocumentFile treeUri)
{
if (treeUri == null)
return "";
var path1 = treeUri.Uri.Path;
if (path1.StartsWith("/tree/"))
{
var path2 = path1.Remove(0, "/tree/".Length);
if (path2.StartsWith("primary:"))
{
var primary = path2.Remove(0, "primary:".Length);
if (primary.Contains(':'))
{
var storeName = "/storage/emulated/0/";
var last = path2.Split(':').LastOrDefault();
var realPath = storeName + last;
return realPath;
}
}
else
{
if (path2.Contains(':'))
{
var path3 = path2.Split(':').FirstOrDefault();
var storeName = path3;
var last = path2.Split(':').LastOrDefault();
var realPath = "/" + storeName + "/" + last;
return realPath;
}
}
}
return path1;
}