java.io.FileNotFoundException: open failed: EACCES (Permission denied)

三世轮回 提交于 2020-05-09 06:32:38

问题


I got this error when I trying to storage a bitmap into storage

     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;
    }

fos =new BufferedOutputStream(new FileOutputStream(imagePath));[I debug and found this line cause the error]

And in manifest the permission set is right


回答1:


This issue is in Android Pie and higher version. So, adding this line in manifest file fixed error.

<application
    ...
    ...
    android:requestLegacyExternalStorage="true">
</application>



回答2:


The problem is my permission format was wrong

Uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE

The android.permission should be lowercase

uses-permission android:name=android.permission.WRITE_EXTERNAL_STORAGE

and if I add imagePath.createNewFile();

it's also throws FileNotFoundExceptions.




回答3:


on Android10

use method -> Environment.getExternalStoragePublicDirectory()

java.io.FileNotFoundException: /storage/emulated/0/Download open failed: EACCES (Permission denied)

Before your app is fully compatible with scoped storage, you can temporarily opt out based on your app's target SDK level or the requestLegacyExternalStorage manifest attribute:

Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:


<manifest ... >
  <!-- This attribute is "false" by default on apps targeting
       Android 10 or higher. -->
  <application android:requestLegacyExternalStorage="true" ... >
    ...
  </application>
</manifest>


来源:https://stackoverflow.com/questions/32524001/java-io-filenotfoundexception-open-failed-eacces-permission-denied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!