从标题中可以看到,我在Android中将文件写入sdcard时遇到问题.我想写入将在sdcard上的公共空间中的文件,以便任何其他应用程序都可以读取它。
首先,我检查sdcard是否已安装:
Environment.getExternalStorageState();
然后,我运行以下代码:
File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
baseDir.mkdirs();
File file = new File(baseDir, "file.txt");
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
Log.d("NEWFILE", file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
我有:
...
在我的AndroidManifest.xml中。
确切的错误是这样的:
java.io.FileNotFoundException: /storage/1510-2908/Download/secondFile.txt: open failed: EACCES (Permission denied)
我正在模拟器上测试代码(模拟Nexus5 API 23)。我要求的最低SDK版本是19(4.4 Kitkat)。
另外,使用相同的代码将文件写入sdcard上的私有文件夹,一切都可以正常工作,所以我想说以前的代码也应该可以工作:
File newFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "esrxdtcfvzguhbjnk.txt");
newFile.getParentFile().mkdirs();
try {
FileOutputStream out = new FileOutputStream(newFile);
out.flush();
out.close();
Log.d("NEWFILE", newFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
有谁知道这可能是什么问题吗?可能是KitKat 4.4不再允许以sdcard写入公共空间了吗?