如何从文档 URI 获取孩子的文档文件



假设以下文件夹结构:

- root
-- Android
-- Downloads
-- ....
-- Test
--- Example
---- Dir1

给定下面列出的Uri,如何获取位于/Test/Example路径的目录的DocumentFile,其中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目录的DocumentFile,因为我需要进一步向下遍历树,并查找/检查是否存在其他目录,例如/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");
    }
}

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

最新更新