首页 文章

尝试将文件写入Android中的SD卡时,FileNotFoundException(权限被拒绝)

提问于
浏览
13

正如你可以从 Headers 中注意到的那样,我在Android中将文件写入sdcard时遇到了问题 . 我已经检查了this question但它没有帮助我 . 我想写一个将在sdcard上的公共空间中的文件,以便任何其他应用程序都可以读取它 .

首先,我检查是否安装了SD卡:

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) .


此外,一切正常,使用相同的代码将文件写入SD卡上的私人文件夹,所以我说前代码也应该工作:

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中写入公共空间或者?

1 回答

  • 21

    将文件写入SD卡上的私人文件夹,一切正常

    从Android 4.4开始,如果您只读取或写入应用程序专用的文件,则不需要这些权限 . 有关更多信息,请参阅saving files that are app-private.

    尝试将文件写入Android中的SD卡时,FileNotFoundException(权限被拒绝)

    当您尝试在具有API 23(Marshmallow)的模拟器中编写文件时,您还需要在运行时请求 WRITE_EXTERNAL_STORAGE 权限 . 有关详细信息,请查看thisthis .

相关问题