Java 如何得到孩子';从文档Uri创建文档文件

Java 如何得到孩子';从文档Uri创建文档文件,java,android,uri,documentfile,scoped-storage,Java,Android,Uri,Documentfile,Scoped Storage,采用以下文件夹结构: - root -- Android -- Downloads -- .... -- Test --- Example ---- Dir1 给定下面列出的Uri,如何获取位于/Test/Example路径的目录的文档文件,其中Test和Example是动态选择的目录 Uri uri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3A/document/primar

采用以下文件夹结构:

- root
-- Android
-- Downloads
-- ....
-- Test
--- Example
---- Dir1
给定下面列出的Uri,如何获取位于
/Test/Example
路径的目录的文档文件,其中Test和Example是动态选择的目录

Uri uri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3A/document/primary%3ATest%2FExample");
DocumentFile f = DocumentFile.fromTreeUri(context, uri);
f.findFile(context, "Dir1"); // Returns null, because the document file is for the primary storage directory
f.findFile(context, "Test"); // Returns the document file for /Test

我需要/Test/Example目录的文档文件,因为我需要进一步遍历树并查找/检查是否存在其他目录,例如
/Test/Example/Dir1/Dir2/Test.txt
,但在运行时之前,我不知道目录的名称。

您仍然可以一次一个目录地从树上下来:

DocumentFile rootDir = DocumentFile.fromTreeUri(context, uri);
if (rootDir != null) {
    DocumentFile testDir = rootDir.findFile(context, "Test");
    if (testDir != null) {
        DocumentFile exampleDir = testDir.findFile(context, "Example");
    }
}

当然,根据您如何获取运行时创建的目录的名称,可能有一种更优雅的方法来实现这一点。

我建议您使用一个更新您的问题,显示如何获取此
Uri
,如何使用
fromTreeUri()
,以及您的意思是什么“但这将返回主存储目录的DocumentFile“。请勿使用
文档文件.findFile
。太慢了。试试看,打100x。@t0m它很慢,你说得对。但是,如果出于某种原因,您不得不使用
文档文件
,那么我不知道找到文件的更好方法。如果你这样做了,我真的很有兴趣读一读。我现在正在解决同样的问题。