我有一个从 ACTION_OPEN_DOCUMENT_TREE
获得的树 URI , 如何在不使用 findFiles()
的情况下获得作为这棵树的子树的 DocumentFile 强>?假设我知道如何获取它的 documentId、它的绝对路径或它的 URI。我需要与文档树关联的权限。
这是我现在拥有的:
DocumentFile rootTree = DocumentFile.fromTreeUri(context, rootTreeUri);
DocumentFile docFile = rootTree.findFile(fileName);
它返回 docFile
作为 TreeDocumentFile,我根的 child 。我有写权限,可以使用 createFile()
在它上面,因为它在 ACTION_OPEN_DOCUMENT_TREE
的文档树下.
所以它有效但是findFile()
真的很慢。
如果我尝试像这样使用 DocumentsContract:
// I know how to build the documentId from the file's absolute path
Uri uri = DocumentsContract.buildTreeDocumentUri(rootTreeUri.getAuthority(), documentId);
DocumentFile docFile = DocumentFile.fromTreeUri(context, uri);
// Result: "content://com.android.externalstorage.documents/tree/1A0E-0E2E:myChildDirectory/document/1A0E-0E2E:myChildDirectory"
它返回一个以 docFile
为根的新 TreeDocumentFile , 不是 docFile
作为我的原始文档树(根)的 child 。所以我没有这棵树的写权限。
如果我这样尝试:
Uri docUri = DocumentsContract.buildDocumentUriUsingTree(rootTreeUri, documentId);
// Result: "content://com.android.externalstorage.documents/tree/1A0E-0E2E:/document/1A0E-0E2E:myChildDirectory"
我得到一个实际上看起来像我想要的 URI,但它是一个 URI,而不是一个 DocumentFile。
如果我执行与上面相同的操作,但使用 fromTreeUri() 从这个 uri 构建一个 DocumentFile:
Uri docUri = DocumentsContract.buildDocumentUriUsingTree(rootTreeUri, documentId);
DocumentFile docFile = DocumentFile.fromTreeUri(context, docUri);
// Result: "content://com.android.externalstorage.documents/tree/1A0E-0E2E:/document/1A0E-0E2E:"
我得到的是原始树 DocumentFile,而不是代表 child 的 DocumentFile。
最佳答案
当前的 API 无法满足您的需求。获得 TreeDocumentFile 的唯一方法(DocumentFile
的私有(private)子类,支持createFile
、createDirectory
、listFiles
和renameTo
) 是通过 DocumentFile.fromTreeUri
(它只为您提供您找到的根树 URI)或通过现有 TreeDocumentFile
的 listFiles()
方法,这是 findFile
内部使用的方法。
您应该在 issuetracker.google.com 上提交功能请求添加一个新的静态方法来满足您的需要。
关于java - 在不使用 findFiles() 的情况下获取作为文档树子项的 DocumentFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46180851/