在 Android 中尝试将文件写入 sdcard 时出现 FileNotFoundException(权限被拒绝)

FileNotFoundException (permission denied) when trying to write file to sdcard in Android

正如您从标题中看到的,我在 Android 中将文件写入 sdcard 时遇到问题。我检查了 this question 但它对我没有帮助。我想在 SD 卡上写入 public space 中的文件,以便任何其他应用程序都可以读取它。

首先,我检查一下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();
    }

我有:

<manifest>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application>
...
</application>
</manifest>

在我的 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 中写入 public space 或者?

  1. Everything works fine with writing files to private folder on sdcard

从 Android 4.4 开始,如果您是 只读取或写入您的应用程序私有的文件。有关详细信息,请参阅 saving files that are app-private.

  1. FileNotFoundException (permission denied) when trying to write file to sdcard in Android

当您尝试在具有 API 23(Marshmallow) 的模拟器中写入文件时,您还需要在运行时请求 WRITE_EXTERNAL_STORAGE 权限。查看 this and this 了解更多详情。