首页 > 解决方案 > 如何访问特定文件夹并使用 Scoped Storage 将文件写入其中

问题描述

我的应用程序具有将 txt 格式的 GPS 数据导出到共享文件夹(现在使用 访问getExternalStorageDirectory)的功能,我必须将其切换到 Scoped Storage (API 30)。(作为信息,该应用程序是适用于 Android
的开源GPS 记录器。)

将来我会让用户选择用于导出的文件夹,使用:

public void openDirectory(Uri uriToLoad) {
    // Choose a directory using the system's file picker.
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, your-request-code);
}

public void onActivityResult(int requestCode, int resultCode,
        Intent resultData) {
    if (requestCode == your-request-code && resultCode == Activity.RESULT_OK) {
        // The result data contains a URI for the directory that the user selected.
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            // Perform operations on the document using its URI.
        }
    }
}

这样我的应用程序将获得对所选文件夹的访问权限。

如何在该文件夹中创建一个文本文件并使用BufferedWriter?

我知道也许我可以使用类似的东西:

...
Uri fileUri = // Something related to the previous uri, but I cannot find the solution
OutputStream outputStream = getContentResolver().openOutputStream(fileUri, "rw");
txtBW = new BufferedWriter(new OutputStreamWriter(outputStream));
...

但我发现没有任何效果。

标签: javaandroidfilescoped-storageaction-open-document-tree

解决方案


DocumentFile是 Google 在文档树中导航的有点笨拙的解决方案。你想要的食谱应该是:

  • Uri你为你的树得到的东西包装在一个DocumentFileusing 中DocumentFile.fromTreeUri()
  • 调用createFile()DocumentFile,提供文件名或其他显示名称,这将为您提供DocumentFile代表该文档
  • 调用getUri()文档DocumentFile以获取Uri代表文档
  • 使用openOutputStream()on aContentResolver将您想要的内容写入该Uri

请注意,如果您需要长期访问此树,请务必调用takePersistableUriPermission()aContentResolver,并传入Uri文档树的 。这应该使您可以访问树和其中的所有文档。


推荐阅读