Exception 'open failed: EACCES (Permission denied)' on Android

AndroidAndroid 5.0-LollipopAndroid PermissionsAndroid Storage

Android Problem Overview


I am getting

> open failed: EACCES (Permission denied)

on the line OutputStream myOutput = new FileOutputStream(outFileName);

I checked the root, and I tried android.permission.WRITE_EXTERNAL_STORAGE.

How can I fix this problem?

try {
    InputStream myInput;

    myInput = getAssets().open("XXX.db");

    // Path to the just created empty db
    String outFileName = "/data/data/XX/databases/"
            + "XXX.db";

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // Transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
    buffer = null;
    outFileName = null;
}
catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

Android Solutions


Solution 1 - Android

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 Q. -->
    <application android:requestLegacyExternalStorage="true" ... >
     ...
    </application>
</manifest>

You can read more about it here: https://developer.android.com/training/data-storage/use-cases

Edit: I am starting to get downvotes because this answer is out of date for Android 11. So whoever sees this answer please go to the link above and read the instructions.

Solution 2 - Android

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

AndroidManifest.xml

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

For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html

Solution 3 - Android

I had the same problem... The <uses-permission was in the wrong place. This is right:

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

The uses-permission tag needs to be outside the application tag.

Solution 4 - Android

Add android:requestLegacyExternalStorage="true" to the Android Manifest It's worked with Android 10 (Q) at SDK 29+
or After migrating Android X.

 <application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:hardwareAccelerated="true"
    android:icon=""
    android:label=""
    android:largeHeap="true"
    android:supportsRtl=""
    android:theme=""
    android:requestLegacyExternalStorage="true">

Solution 5 - Android

I have observed this once when running the application inside the emulator. In the emulator settings, you need to specify the size of external storage ("SD Card") properly. By default, the "external storage" field is empty, and that probably means there is no such device and EACCES is thrown even if permissions are granted in the manifest.

Solution 6 - Android

In addition to all the answers, make sure you're not using your phone as a USB storage.

I was having the same problem on HTC Sensation on USB storage mode enabled. I can still debug/run the app, but I can't save to external storage.

Solution 7 - Android

My issue was with "TargetApi(23)" which is needed if your minSdkVersion is bellow 23.

So, I have request permission with the following snippet

protected boolean shouldAskPermissions() {
    return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}

@TargetApi(23)
protected void askPermissions() {
    String[] permissions = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };
    int requestCode = 200;
    requestPermissions(permissions, requestCode);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
// ...
    if (shouldAskPermissions()) {
        askPermissions();
    }
}

Solution 8 - Android

Be aware that the solution:

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

Is temporary, sooner or later your app should be migrated to use Scoped Storage.

In Android 10, you can use the suggested solution to bypass the system restrictions, but in Android 11 (R) it is mandatory to use scoped storage, and your app might break if you kept using the old logic!

This video might be a good help.

Solution 9 - Android

Android 10 (API 29) introduces Scoped Storage. Changing your manifest to request legacy storage is not a long-term solution.

I fixed the issue when I replaced my previous instances of Environment.getExternalStorageDirectory() (which is deprecated with API 29) with context.getExternalFilesDir(null).

Note that context.getExternalFilesDir(type) can return null if the storage location isn't available, so be sure to check that whenever you're checking if you have external permissions.

Read more here.

Solution 10 - Android

I'm experiencing the same. What I found is that if you go to Settings -> Application Manager -> Your App -> Permissions -> Enable Storage, it solves the issue.

Solution 11 - Android

It turned out, it was a stupid mistake since I had my phone still connected to the desktop PC and didn't realize this.

So I had to turn off the USB connection and everything worked fine.

Solution 12 - Android

I had the same problem on Samsung Galaxy Note 3, running CM 12.1. The issue for me was that i had

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

and had to use it to take and store user photos. When I tried to load those same photos in ImageLoader i got the (Permission denied) error. The solution was to explicitly add

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

since the above permission only limits the write permission up to API version 18, and with it the read permission.

Solution 13 - Android

In addition to all answers, if the clients are using Android 6.0, Android added new permission model for (Marshmallow).

Trick: If you are targeting version 22 or below, your application will request all permissions at install time just as it would on any device running an OS below Marshmallow. If you are trying on the emulator then from android 6.0 onwards you need to explicitly go the settings->apps-> YOURAPP -> permissions and change the permission if you have given any.

Solution 14 - Android

Strangely after putting a slash "/" before my newFile my problem was solved. I changed this:

File myFile= new File(Environment.getExternalStorageDirectory() + "newFile");

to this:

File myFile= new File(Environment.getExternalStorageDirectory() + "/newFile");

UPDATE: as mentioned in the comments, the right way to do this is:

File myFile= new File(Environment.getExternalStorageDirectory(), "newFile");

Solution 15 - Android

I had the same problem and none of suggestions helped. But I found an interesting reason for that, on a physical device, Galaxy Tab.

When USB storage is on, external storage read and write permissions don't have any effect. Just turn off USB storage, and with the correct permissions, you'll have the problem solved.

Solution 16 - Android

I would expect everything below /data to belong to "internal storage". You should, however, be able to write to /sdcard.

Solution 17 - Android

Change a permission property in your /system/etc/permission/platform.xml
and group need to mentioned as like below.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
    <group android:gid="sdcard_rw" />
    <group android:gid="media_rw" />    
</uses-permission>

Solution 18 - Android

I had the same error when was trying to write an image in DCIM/camera folder on Galaxy S5 (android 6.0.1) and I figured out that only this folder is restricted. I simply could write into DCIM/any folder but not in camera. This should be brand based restriction/customization.

Solution 19 - Android

Maybe the answer is this:

on the API >= 23 devices, if you install app (the app is not system app), you should check the storage permission in "Setting - applications", there is permission list for every app, you should check it on! try

Solution 20 - Android

When your application belongs to the system application, it can't access the SD card.

Solution 21 - Android

keep in mind that even if you set all the correct permissions in the manifest: The only place 3rd party apps are allowed to write on your external card are "their own directories" (i.e. /sdcard/Android/data/) trying to write to anywhere else: you will get exception: EACCES (Permission denied)

Solution 22 - Android

Environment.getExternalStoragePublicDirectory();

When using this deprecated method from Android 29 onwards you will receive the same error:

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

Resolution here:

https://stackoverflow.com/questions/56468539/getexternalstoragepublicdirectory-deprecated-in-android-q

Solution 23 - Android

To store a file in a directory which is foreign to the app's directory is restricted above API 29+. So to generate a new file or to create a new file use your application directory like this :-

So the correct approach is :-

val file = File(appContext.applicationInfo.dataDir + File.separator + "anyRandomFileName/")

You can write any data into this generated file !

The above file is accessible and would not throw any exception because it resides in your own developed app's directory.

The other option is android:requestLegacyExternalStorage="true" in manifest application tag as suggested by Uriel but its not a permanent solution !

Solution 24 - Android

In my case I was using a file picker library which returned the path to external storage but it started from /root/. And even with the WRITE_EXTERNAL_STORAGE permission granted at runtime I still got error EACCES (Permission denied).
So use Environment.getExternalStorageDirectory() to get the correct path to external storage.

Example:
Cannot write: /root/storage/emulated/0/newfile.txt
Can write: /storage/emulated/0/newfile.txt

boolean externalStorageWritable = isExternalStorageWritable();
File file = new File(filePath);
boolean canWrite = file.canWrite();
boolean isFile = file.isFile();
long usableSpace = file.getUsableSpace();

Log.d(TAG, "externalStorageWritable: " + externalStorageWritable);
Log.d(TAG, "filePath: " + filePath);
Log.d(TAG, "canWrite: " + canWrite);
Log.d(TAG, "isFile: " + isFile);
Log.d(TAG, "usableSpace: " + usableSpace);

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

Output 1:

externalStorageWritable: true
filePath: /root/storage/emulated/0/newfile.txt
isFile: false
usableSpace: 0

Output 2:

externalStorageWritable: true
filePath: /storage/emulated/0/newfile.txt
isFile: true
usableSpace: 1331007488

Solution 25 - Android

I am creating a folder under /data/ in my init.rc (mucking around with the aosp on Nexus 7) and had exactly this problem.

It turned out that giving the folder rw (666) permission was not sufficient and it had to be rwx (777) then it all worked!

Solution 26 - Android

The post 6.0 enforcement of storage permissions can be bypassed if you have a rooted device via these adb commands:

root@msm8996:/ # getenforce
getenforce
Enforcing
root@msm8996:/ # setenforce 0
setenforce 0
root@msm8996:/ # getenforce
getenforce
Permissive

Solution 27 - Android

I Use the below process to handle the case with android 11 and targetapi30

  1. As pre-created file dir as per scoped storage in my case in root dir files//

  2. Copy picked file and copy the file in cache directory at the time of picking from my external storage

  3. Then at a time to upload ( on my send/upload button click) copy the file from cache dir to my scoped storage dir and then do my upload process

use this solution due to at time upload app in play store it generates warning for MANAGE_EXTERNAL_STORAGE permission and sometimes rejected from play store in my case.

Also as we used target API 30 so we can't share or forward file from our internal storage to app

Solution 28 - Android

Add Permission in manifest.

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

Solution 29 - Android

I had the same problem (API >= 23).

The solution https://stackoverflow.com/a/13569364/1729501 worked for me, but it was not practical to disconnect app for debugging.

my solution was to install proper adb device driver on Windows. The google USB driver did not work for my device.

STEP 1: Download adb drivers for your device brand.

STEP 2: Go to device manager -> other devices -> look for entries with word "adb" -> select Update driver -> give location in step 1

Solution 30 - Android

Add gradle dependencies

implementation 'com.karumi:dexter:4.2.0'

Add below code in your main activity.

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {


                checkMermission();
            }
        }, 4000);
	}

    private void checkMermission(){
        Dexter.withActivity(this)
                .withPermissions(
                        android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.ACCESS_NETWORK_STATE,
                        Manifest.permission.INTERNET
                ).withListener(new MultiplePermissionsListener() {
            @Override
            public void onPermissionsChecked(MultiplePermissionsReport report) {
                if (report.isAnyPermissionPermanentlyDenied()){
                    checkMermission();
                } else if (report.areAllPermissionsGranted()){
					// copy some things
                } else {
                    checkMermission();
                }

            }
            @Override
            public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                token.continuePermissionRequest();
            }
        }).check();
    }

Solution 31 - Android

Building on answer by user462990

To be notified when the user responds to the permission request dialog, use this: (code in kotlin)

override fun onRequestPermissionsResult(requestCode: Int,
                                        permissions: Array<String>,
                                        grantResults: IntArray) {
    when (requestCode) {
        MY_PERMISSIONS_REQUEST_READ_CONTACTS -> {
            // If request is cancelled, the result arrays are empty.
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.

            }
            return
        }

        // Add other 'when' lines to check for other
        // permissions this app might request.

        else -> {
                // Ignore all other requests.
        }   
    }
}

Solution 32 - Android

In my case the error was appearing on the line

      target.createNewFile();

since I could not create a new file on the sd card,so I had to use the DocumentFile approach.

      documentFile.createFile(mime, target.getName());

For the above question the problem may be solved with this approach,

    fos=context.getContentResolver().openOutputStream(documentFile.getUri());

See this thread too, https://stackoverflow.com/questions/26744842/how-to-use-the-new-sd-card-access-api-presented-for-android-5-0-lollipop

Solution 33 - Android

i faced the same error on xiaomi devices (android 10 ). The following code fixed my problem. Libraries: Dexter(https://github.com/Karumi/Dexter) and Image picker(https://github.com/Dhaval2404/ImagePicker)

Add manifest ( android:requestLegacyExternalStorage="true")

    public void showPickImageSheet(AddImageModel model) {
    BottomSheetHelper.showPickImageSheet(this, new BottomSheetHelper.PickImageDialogListener() {
        @Override
        public void onChooseFromGalleryClicked(Dialog dialog) {
            selectedImagePickerPosition = model.getPosition();
            Dexter.withContext(OrderReviewActivity.this)                   .withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .withListener(new MultiplePermissionsListener() {
                        @Override
                        public void onPermissionsChecked(MultiplePermissionsReport report) {
                            if (report.areAllPermissionsGranted()) {
                                ImagePicker.with(OrderReviewActivity.this)
                                        .galleryOnly()
                                        .compress(512)
                                        .maxResultSize(852,480)
                               .start();
                            }
                        }

                        @Override
                        public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
                            permissionToken.continuePermissionRequest();
                        }

                    }).check();

            dialog.dismiss();
        }

        @Override
        public void onTakePhotoClicked(Dialog dialog) {
            selectedImagePickerPosition = model.getPosition();
            ImagePicker.with(OrderReviewActivity.this)
                    .cameraOnly()
                    .compress(512)
                    .maxResultSize(852,480)
                    .start();

            dialog.dismiss();
        }

        @Override
        public void onCancelButtonClicked(Dialog dialog) {
            dialog.dismiss();
        }
    });
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMertView Question on Stackoverflow
Solution 1 - AndroidUriel FrankelView Answer on Stackoverflow
Solution 2 - AndroidJustin FiedlerView Answer on Stackoverflow
Solution 3 - Androiduser462990View Answer on Stackoverflow
Solution 4 - AndroidrhaldarView Answer on Stackoverflow
Solution 5 - AndroidAudrius MeškauskasView Answer on Stackoverflow
Solution 6 - AndroidjohnView Answer on Stackoverflow
Solution 7 - AndroidPiroxiljinView Answer on Stackoverflow
Solution 8 - AndroidomzerView Answer on Stackoverflow
Solution 9 - AndroidjacoballenwoodView Answer on Stackoverflow
Solution 10 - AndroidAtul KaushikView Answer on Stackoverflow
Solution 11 - AndroidTobias ReichView Answer on Stackoverflow
Solution 12 - AndroidZooSView Answer on Stackoverflow
Solution 13 - AndroidNourdine AlouaneView Answer on Stackoverflow
Solution 14 - AndroidDarushView Answer on Stackoverflow
Solution 15 - AndroidHamlet KraskianView Answer on Stackoverflow
Solution 16 - AndroidovenrorView Answer on Stackoverflow
Solution 17 - AndroidPrabakaranView Answer on Stackoverflow
Solution 18 - AndroidMahdi MehriziView Answer on Stackoverflow
Solution 19 - AndroidJason ZhuView Answer on Stackoverflow
Solution 20 - AndroidwillView Answer on Stackoverflow
Solution 21 - AndroidEladView Answer on Stackoverflow
Solution 22 - Androiduser2965003View Answer on Stackoverflow
Solution 23 - AndroidSantanu SurView Answer on Stackoverflow
Solution 24 - AndroidvovahostView Answer on Stackoverflow
Solution 25 - AndroidlaneView Answer on Stackoverflow
Solution 26 - AndroidZakirView Answer on Stackoverflow
Solution 27 - AndroidArpan24x7View Answer on Stackoverflow
Solution 28 - AndroidHarman KheraView Answer on Stackoverflow
Solution 29 - Androiduser13107View Answer on Stackoverflow
Solution 30 - AndroidethemsulanView Answer on Stackoverflow
Solution 31 - Androiduser3561494View Answer on Stackoverflow
Solution 32 - AndroidTarasantanView Answer on Stackoverflow
Solution 33 - AndroidYasin EgeView Answer on Stackoverflow