9

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

Boken
  • 4,825
  • 10
  • 32
  • 42
Alexander
  • 141
  • 1
  • 1
  • 6

3 Answers3

19

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

<application
    ...
    ...
    android:requestLegacyExternalStorage="true">
</application>
F_Z
  • 581
  • 3
  • 16
10

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>
Mahmoud Zaher
  • 559
  • 6
  • 6
4

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.

Pankaj
  • 7,908
  • 6
  • 42
  • 65
Alexander
  • 141
  • 1
  • 1
  • 6