[java] java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

I've been trying to encrypt files and write those files back on to the same place. But I got the error message saying "java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)".

My Manifest file is this

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tdk.mytestapplication2">

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


<application
    android:allowBackup="true"

I think I have provided correct permission there. And the code I am using to encrypt files is this.

public static void encrypt(SecretKey secretKey, String filePath){
    try {
        // Here you read the cleartext.
        FileInputStream fis = new FileInputStream(filePath);
        // This stream write the encrypted text. This stream will be wrapped by another stream.
        FileOutputStream fos = new FileOutputStream(filePath);

        // Create cipher
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        // Wrap the output stream
        CipherOutputStream cos = new CipherOutputStream(fos, cipher);

        // Write bytes
        int b;
        byte[] d = new byte[8];
        while ((b = fis.read(d)) != -1) {
            cos.write(d, 0, b);
        }

        // Flush and close streams.
        cos.flush();
        cos.close();
        fis.close();

    }catch(IOException e){
        e.printStackTrace();
    }catch (NoSuchAlgorithmException e){
        e.printStackTrace();
    }catch(NoSuchPaddingException e){
        e.printStackTrace();
    }catch(InvalidKeyException e){
        e.printStackTrace();
    }
}

And I used this method inside a button

Button btnEncrypt = (Button) findViewById(R.id.btnEnc);
    btnEncrypt.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            aesKey = EncAndDec.generateKey();
            String filePath = editText.getText().toString();
            //Generating the file hash
            String md5Hash = MD5Hash.getMD5(filePath);

            System.out.println(aesKey.toString());
            System.out.println(filePath);
            System.out.println(md5Hash);

            //Encrypting the file
            for(int i=1; i<100; i++) {
                EncAndDec.encrypt(aesKey, filePath);
            }
        }
    });

Still I couldn't configure this error. Please someone help!

This question is related to java android android-permissions

The answer is


I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.


For SDK 29 :

String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}

public static void createTextFile(String sBody, String FileName, String Where) {
    try {
        File gpxfile = new File(Where, FileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you can save your file like this :

createTextFile("This is Content","file.txt",str1);

Implement runtime permission for running your app on Android 6.0 Marshmallow (API 23) or later.

or you can manually enable the storage permission-

goto settings>apps> "your_app_name" >click on it >then click permissions> then enable the storage. Thats it.

But i suggest go the for first one which is, Implement runtime permissions in your code.


If you are running in Android 29 then you have to use scoped storage or for now, you can bypass this issue by using:

android:requestLegacyExternalStorage="true"

in manifest in the application tag.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-permissions

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied) Android 6.0 multiple permissions Android marshmallow request permission? How to programmatically open the Permission Screen for a specific app on Android Marshmallow? Android M Permissions: onRequestPermissionsResult() not being called Android M - check runtime permission - how to determine if the user checked "Never ask again"? How to check Grants Permissions at Run-Time? How to detect incoming calls, in an Android device? Exception 'open failed: EACCES (Permission denied)' on Android What permission do I need to access Internet from an Android application?