我正在使用意图ACTION_OPEN_DOCUMENT_TREE,它在活动结果中给出了文件夹的路径。但是,在指定的文件夹中搜索文件是不正确的。
上下文:我正在构建一个应用程序,允许用户选择程序将搜索文件类型的目录,但是从data.Getdata()收到的路径是不正确的。你知道该怎么做吗?
我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
//some lines of code
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(intent, 0);}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data)
if (data != null) {
Uri uri_1= data.getData();
String path=uri_1.getPath();;
File custom_file=new File(path);
//searching for specific file type in given folder
ArrayList<File> my_files= fetch_files(custom_file);
//rest of code to what to do with files I received from fetch_files
}
发布于 2022-10-13 22:53:46
我使用的是意图ACTION_OPEN_DOCUMENT_TREE,它在活动结果中给出了文件夹的路径
不,不需要。它为文档集合提供了一个Uri
。
从data.Getdata()接收的路径不正确
它不是文件系统路径。它不应该是文件系统路径。例如,https://stackoverflow.com/questions/74062576/android-studio-how-to-get-storage-path-from-intent-action-open-document-tree
是一个Uri
,而/questions/74062576/android-studio-how-to-get-storage-path-from-intent-action-open-document-tree
不是您手机上的文件系统路径。
如果您想使用该Uri
进行操作,请调用DocumentFile.fromTreeUri()
,传入您的Uri
,以获得表示该文档树的DocumentFile
。DocumentFile
为您提供了一个类似于File
的API,但它可以处理存储访问框架中的文档和树。
发布于 2022-10-13 22:53:06
它通常返回以/tree/开头的路径,因此需要将其转换为/storage/ path,以便读取您的文件。我从一位同事那里找到了一段代码(链接:https://stackoverflow.com/a/65934369/20046611),但我稍微修改了一下。
public String GetRealPath(Uri treeUri)
{
if (treeUri == null)
return "";
String path1=treeUri.getPath();
if (path1.startsWith("/tree/"))
{
String path2= path1.replace("/tree/","");
if (path2.startsWith("primary:"))
{
String primary = path2.replace("primary:","");
if (primary.contains(":"))
{
String storeName = "/storage/emulated/0/";
String[] last = path2.split(":");
String realPath = storeName + last[1];
return realPath;
}
else{
String storeName = "/storage/emulated/0/";
String[] last = path2.split(":");
String realPath = storeName + last[1];
return realPath;
}
}
else
{
if (path2.contains(":"))
{
String[] path3 = path2.split(":");
String storeName = path3[0];
String[] last = path2.split(":");
String realPath = "/" + storeName + "/" + last[1];
return realPath;
}
}
}
return path1;
}
您所需要做的就是输入String path=GetRealPath(uri_1);
以获得能够工作的路径。
https://stackoverflow.com/questions/74062576
复制相似问题