【发布时间】:2018-08-19 09:04:42
【问题描述】:
我正在尝试将公共文件保存在外部存储上。 我正在关注 Android Developers 页面中的示例: https://developer.android.com/training/data-storage/files#PublicFiles
首先我尝试在公共目录 DIRECTORY_DOCUMENTS 中创建一个目录“mydocuments”。代码很简单
TextView tv= findViewById(R.id.myTextview);
// Get the directory for the user's public pictures directory.
File documents= Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
tv.append("\n documents directory=" + documents);
File file = new File(documents, "mydocuments");
tv.append("\n\nDirectory to be created=" + file);
if (file.exists())
tv.append("\n\nFile already exists:" + file.getAbsolutePath());
else{
if (!file.mkdirs())
tv.append("\n\nDirectory not created:" + file.getAbsolutePath());
我在清单文件中添加了权限
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
但是,当我在设备(虚拟或物理)中运行它时,结果总是相同的:
documents directory=/storage/emulated/0/Documents
Directory to be created=/storage/emulated/0/Documents/mydocuments
Directory not created:/storage/emulated/0/Download/mydocuments
如何使 Documents 目录可写?
提前谢谢你。
【问题讨论】:
-
documents=/storage/emulated/0/Documents Directory not created这是发布问题的一种令人困惑的方式,因为未创建的目录是/storage/emulated/0/Documents/mydocuments -
tv.append("Directory not created");改为tv.append("Directory not created: " + file.getAbsolutePath()); -
进一步:您从官方谷歌文档复制了这段代码。它的代码非常糟糕,因为当目录已经存在时,您将收到一条消息,指出该目录未创建。如果目录还不存在,您应该只调用 mkdir()/mkdirs()。所以使用前请检查。
-
谢谢,我将上面的代码编辑为更清晰的内容,包括检查目录是否存在。
标签: android android-sdcard android-external-storage readonly-attribute