從標題中可以看到,我在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寫入公共空間了嗎?