簡體   English   中英

如何從 Document Uri 獲取孩子的 DocumentFile

[英]How to get child's DocumentFile from Document 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");
    }
}

當然,根據您如何獲取運行時創建的目錄的名稱,可能有一種更優雅的方法來執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM