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

520,953

Solution 1

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 2

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 3

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 4

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

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.

Share:
520,953
Mert
Author by

Mert

Updated on November 29, 2021

Comments

  • Mert
    Mert over 2 years

    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();
    }
    
  • Mert
    Mert over 12 years
    I tried <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> too. still same.
  • ovenror
    ovenror over 12 years
    The /data-partition is generally write-protected to ordinary (non-root) users trying to to ordinary file access. For internal storage, there are specialized methods to do so, especially if you want to access databases. The Android developer pages should help you on this issue.
  • user462990
    user462990 about 12 years
    it is that the uses-permission needs to be outside the application
  • John
    John almost 10 years
    platform.xml is locked right down, attempting this through adb shell but need whatever script ADB will let me use for the mod.
  • mr5
    mr5 over 9 years
    I get a warning: "<uses-permission> tag appears after <application> tag"
  • guisantogui
    guisantogui over 9 years
    WARNING In android 4.4.4 do not use the parameter android:maxSdkVersion="18". It was generating this exception
  • andrei_zaitcev
    andrei_zaitcev over 9 years
    @guisantogui, thank you! You save me a lot of hours of debugging while I don't understand while my app doesn't have the permission to write to the external storage.
  • rbennett485
    rbennett485 about 9 years
    @guisantogui same job for me, but on Android 5.0.1. I was following the official tutorial which explicitly says to include android:maxSdkVersion="18" for android 4.4 onwards, but obviously that isn't true
  • Zar E Ahmer
    Zar E Ahmer almost 9 years
    This permission is enforced starting in API level 19. Before API level 19, this permission is not enforced and all apps still have access to read from external storage.
  • Ravi Mehta
    Ravi Mehta over 8 years
    i m using API lvl 15 , i m getting error while attempting to move file to OTG USB Stick
  • kldavis4
    kldavis4 over 8 years
    Just to clarify, in order for this to work, the activity must handle the activity permissions request response. See developer.android.com/training/permissions/… for more details.
  • Paul Alexander
    Paul Alexander over 8 years
    Handy link with explanation and examples here inthecheesefactory.com/blog/…
  • M. Usman Khan
    M. Usman Khan over 8 years
    isn't this a bad thing? with respect to user experience.
  • ocramot
    ocramot about 8 years
    @usman wrt user experience, it is meant to be a good thing, since the user will be able to grant a single permission every time instead that all togheter, and the user would have a better understanding of what the application is doing on their phone. It will instead be a bad thing for user experience because the user will accept every permission request nevertheless, without even caring.
  • Admin
    Admin about 8 years
    But where do I use it? for example, if I want to take a picture, do I have to run verifyStoragePermissions before startActivityForResult, or at onActivityResult? it really confuses me.
  • Ashwin Shirva
    Ashwin Shirva almost 8 years
    @Kiwi Lee you must use it before you decode your image. ie before using decodeFile(filepath) method
  • Oubaida AlQuraan
    Oubaida AlQuraan almost 8 years
    Thanks this solve my problem. just a note: if someone can't resolve "Manifest.permission" you just need to import "import android.Manifest".
  • Sharp Edge
    Sharp Edge over 7 years
    Thanks man, Even though i had requested permissions from user at runtime. This error occurred on emulator.
  • crgarridos
    crgarridos over 7 years
    Damn it, I just spent like 3 hours working around. Aditionally, I had to reboot the device and it did work. Thank you so much
  • Raphael Royer-Rivard
    Raphael Royer-Rivard over 7 years
    You do not need to add READ_EXTERNAL_STORAGE, as WRITE_EXTERNAL_STORAGE counts as both. Source from official documentation developer.android.com/training/basics/data-storage/…
  • Testing Singh
    Testing Singh over 7 years
    When I connect the Samsung Galaxy S6 device it first gives an option "Allow access to device data" with "DENY" or "ALLOW" and also from notification bar I am getting an option Use USB for 1. MTP 2. PTP 3. MIDI Devices 4. Charging. Which one to choose?
  • Peter Chaula
    Peter Chaula over 7 years
    Very hard to find error unless you look at the log cat. It's a bit confusing if you 're using BitmapFactory.decodeFile() as is stays silent about any errors
  • Jaime Ivan Cervantes
    Jaime Ivan Cervantes over 7 years
    Unbelievable, I spent 2 days trying to figure this out. Everytime I feel things are running smoothly on Android, something like this occurs.
  • Tobse
    Tobse over 7 years
    Fail. Put my device into a boot loop.
  • Sakiboy
    Sakiboy about 7 years
    Didn't help me! Worth a try tho! Thanks.
  • Ryan R
    Ryan R about 7 years
    There is no permission android.permission.READ_INTERNAL_STORAGE
  • user13107
    user13107 almost 7 years
    worked for me as well. But why does it work? what difference does not connecting USB to PC make.
  • Tobias Reich
    Tobias Reich almost 7 years
    Good question. I never investigated this any further. I'd guess there is a write lock from the system the moment you connect the device (so it may emulate a usb device on your computer). Maybe this is in order to avoid inconsistent data. Not sure though.
  • user13107
    user13107 almost 7 years
  • Stéphane
    Stéphane almost 7 years
    Nothing strange here. With the first line you are trying to create a file in the same directory as the one that contains your external storage directory. ie /storage/.../somethingnewfile instead of /storage/.../something/newfile
  • Darush
    Darush almost 7 years
    @Stéphane The error itself is strange if you look at the broad range of answers.
  • xabush
    xabush over 6 years
    I was having the same exact problem. Removing the root part from the path resolved my issue.
  • Nick Cardoso
    Nick Cardoso about 6 years
    The correct way to do this is to use the File(dir, file) cosntructor
  • Darush
    Darush about 6 years
    @NickCardoso You can also use File(String pathname). Looks like you are not getting the point here. The question is not about how to use the File class. The range of answers in this thread shows how misleading this error is and how many possible ways of resolving it. In my case the error was the missing slash. Some people have found it useful. Sure you could use your own method of accessing a file. Go ahead and post your answer. It may solves someone's problem.
  • Nick Cardoso
    Nick Cardoso about 6 years
    You are not getting the point. If you use the correct constructor, then your hack is not required. My comment was added so it can help any future readers misled by your mistake. It wasn't a personal criticism and didn't need a reply
  • Darush
    Darush about 6 years
    @NickCardoso you could have suggested an edit instead of posting a comment to prevent readers being mislead by my mistake. You are still confused. If a person used the correct way, as pointed by you, he wouldn't come to this thread at first. I am just suggesting the possible cause of that error and how to solve it.
  • Nick Cardoso
    Nick Cardoso about 6 years
    And they would be coming here to find the correct way. Editing your answer so they never see your mistake wouldn't teach anything.
  • Darush
    Darush about 6 years
    @NickCardoso There is no such thing as absolute correct way. The answers in a thread are just some alternate ways to resolve an issue.
  • Nick Cardoso
    Nick Cardoso about 6 years
    In the case of path construction, there absolutely is a correct way, or an unreliable hack. This conversation is ironic given your profile claims.
  • Evan Sevy
    Evan Sevy about 6 years
    I'm unable to find this section?
  • Uriel Frankel
    Uriel Frankel over 4 years
    @Billy i noticed it is only happens on devices with api 29. So i searched for changes in files provider
  • bko
    bko over 4 years
    Finally got the cloudtestingscreenshotter_lib.aar to work with this line added to the androidTest manifest, thank you very much for this find.
  • sanjeev
    sanjeev over 4 years
    You sir, saved me a lot of time. A lot of things have become a pain for a developer in Q. I think this answer should be posted as a separate question and deserves more upvotes.
  • SadSido
    SadSido about 4 years
    I would like to read more about this nice little black magic trick, but unfortunately the link returns a 404 error ... Thanks anyway
  • Santanu Sur
    Santanu Sur about 4 years
    its giving an warning android:requestLegacyExternalStorage="true" this wont break lower versions ryt ? @UrielFrankel
  • ocramot
    ocramot about 4 years
    Link is still 404; is developer.android.com/training/data-storage#scoped-storage the updated url?
  • Uriel Frankel
    Uriel Frankel about 4 years
    ocramot Fixed the link
  • Mister JJ
    Mister JJ almost 4 years
    Man you saved me. I was trying everything to solve it. I was guessing the problem was Android 10 and you fixed it in just one line thank you (y)
  • Ayush Katuwal
    Ayush Katuwal almost 4 years
    Wow works perfectly, that was the answer I was in seek of, great, thank you @rhaldar, you saved my day
  • Walid
    Walid almost 4 years
    you saved me sir this fixed the problem. But I have a question, I have two exact phones (PH-1) with exact versions (Android 10) but only one of them crache and the other doesn't crash. anyone have any idea why ?
  • Nikmoon
    Nikmoon almost 4 years
    @kldavis4 this is not required now, just request permission
  • Roshana Pitigala
    Roshana Pitigala almost 4 years
    Starting from Android 11 this is no longer valid
  • Brontes
    Brontes over 3 years
    I would like to backup @NickCardoso... When I used File(pathname) constructor I got error... With File(dir, file) constructor everything works...
  • Siddarth G
    Siddarth G over 3 years
    @RoshanaPitigala what needs to be done for android 11 any link?
  • Uriel Frankel
    Uriel Frankel over 3 years
  • touhid udoy
    touhid udoy over 3 years
    you sir saved my whole night...kudos, sault
  • Sujeet
    Sujeet over 3 years
    I'm also facing the same problem and in my code, it is already placed there still getting the same error. The problem is with Android 10 when your app targeting API level 29.
  • Carlos Barcellos
    Carlos Barcellos over 3 years
    After API 29 you will need this: medium.com/@sriramaripirala/…
  • Noor Hossain
    Noor Hossain over 3 years
    ridiculous things from the authority ! extra pain for developers, why ? is this our fault that we came to android ?
  • TootsieRockNRoll
    TootsieRockNRoll almost 3 years
    I shouldn't search for this long to find this answer
  • AMAL MOHAN N
    AMAL MOHAN N almost 3 years
    thank you <3. This is working fine with my devices.
  • Mr. Lemon
    Mr. Lemon over 2 years
    Roshana Pitigala Android 11 you need permission : "android.permission.MANAGE_EXTERNAL_STORAGE"
  • famfamfam
    famfamfam over 2 years
    not working in android 11
  • rhaldar
    rhaldar over 2 years
  • nicolas asinovich
    nicolas asinovich about 2 years
    @Mr. Lemon The Google Play store has a policy that limits usage of MANAGE_EXTERNAL_STORAGE
  • reza rahmad
    reza rahmad about 2 years
    new error came out, ENOENT no file or dictionary
  • Vitaly
    Vitaly almost 2 years
    No. It's not working solution.
  • CodeToLife
    CodeToLife almost 2 years
    @reza rahmad same here
  • CodeToLife
    CodeToLife almost 2 years
    I brought its name out in logs. And now its clear Environment.getExternalStorageDirectory(Environment.***) and context.getExternalFilesDir(Environment.***) are different paths . Thats all. Upvoting.