java.io.FileNotFoundException:打开失败:EACCES(权限被拒绝)

Ale*_*der 9 android fileoutputstream

当我尝试将位图存储到存储中时出现此错误 #

    File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "picture");
    if (! path.exists()) {
        path.mkdirs();
        if (!path.exists()) {
            return null;
        }
    }
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HH_mm_ss", Locale.CHINA).format(new Date());
    File imagePath = new File(path.getPath() + "_" + "IMG_" + timeStamp + ".jpg");
    BufferedOutputStream fos;
    try {
        fos =new BufferedOutputStream(new FileOutputStream(imagePath));
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
        return imagePath;
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
        return null;
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

fos = new BufferedOutputStream(new FileOutputStream(imagePath));

我调试并发现此行导致错误。

在清单中,权限集是正确的

小智 19

此问题出现在 Android Pie 及更高版本中。因此,在清单文件中添加这一行修复了错误。

<application
    ...
    ...
    android:requestLegacyExternalStorage="true">
</application>
Run Code Online (Sandbox Code Playgroud)

  • 这是临时修复,或者直到 Android 11 发布为止。 (3认同)

小智 10

在 Android10 上

use method -> Environment.getExternalStoragePublicDirectory()

java.io.FileNotFoundException: /storage/emulated/0/Download open failed: EACCES (Permission denied)
Run Code Online (Sandbox Code Playgroud)

在您的应用与范围存储完全兼容之前,您可以根据应用的目标 SDK 级别或 requestLegacyExternalStorage 清单属性暂时选择退出:

谷歌在 Android Q 上有一个新功能:外部存储的过滤视图。对此的快速解决方法是在 AndroidManifest.xml 文件中添加以下代码:


<manifest ... >
  <!-- This attribute is "false" by default on apps targeting
       Android 10 or higher. -->
  <application android:requestLegacyExternalStorage="true" ... >
    ...
  </application>
</manifest>
Run Code Online (Sandbox Code Playgroud)


Ale*_*der 4

问题是我的权限格式错误

使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE

应该android.permission是小写

使用权限 android:name=android.permission.WRITE_EXTERNAL_STORAGE

如果我添加imagePath.createNewFile();

它也抛出FileNotFoundExceptions