java - 如何访问特定文件夹并使用 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));
...
但我发现没有任何效果。
解决方案
DocumentFile
是 Google 在文档树中导航的有点笨拙的解决方案。你想要的食谱应该是:
- 把
Uri
你为你的树得到的东西包装在一个DocumentFile
using 中DocumentFile.fromTreeUri()
- 调用
createFile()
它DocumentFile
,提供文件名或其他显示名称,这将为您提供DocumentFile
代表该文档 - 调用
getUri()
文档DocumentFile
以获取Uri
代表文档 - 使用
openOutputStream()
on aContentResolver
将您想要的内容写入该Uri
请注意,如果您需要长期访问此树,请务必调用takePersistableUriPermission()
aContentResolver
,并传入Uri
文档树的 。这应该使您可以访问树和其中的所有文档。
推荐阅读
- postgresql - 为什么 SQLAlchemy 不反映非公共模式中的表?
- ipywidgets - ipywidgets:最小化按钮宽度以仅显示图标?
- php - Symfony 字段表单在 Ajax 之后未提交
- css - 使用@font-face 的大卡特尔自定义字体不起作用
- javascript - 提交按钮不起作用,如何使它起作用?(描述中提供的代码)
- security - 在 Salesforce 中找不到重置安全令牌选项
- java - 在 java spark 中从 REST API 读取 csv
- javascript - 如何检查两个数字是否具有相同的值并将它们存储在 JavaScript 中的 Object 中?
- scala - Hadoop aws 和 spark 不兼容
- python - 如何制作python ursina引擎的立方体纹理