Search code examples
androidandroid-studioandroid-permissionspermission-deniedandroid-external-storage

Android studio getting error IOException: Operation not permitted while creating file for android sdk 31


I am trying to create a file on external storage but I am getting "IOException: Operation not permitted" error. Below is my code

File file = new File(Environment.getExternalStorageDirectory() + "/dummy.txt");
if (!file.exists()){
       file.createNewFile();
}

Below are the permissions I have added to manifest file

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

I have also added checkSelfPermission before creating the file

if(Build.VERSION.SDK_INT >= 23) {
        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
            );
        }
    }

I have set compilesdk and targetsdk version to 31. Even after trying all of this, I am not able to create a directory or a file on external storage. How can I solve this issue?


Solution

  • According to google documentation Starting in Android 11, apps cannot create their own app-specific directory on external storage, and also the same thing for creating files, so to fix this you can create the file in any other directory like downloads directory for example, your code will look like this:

    File file = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/dummy.txt");
    if (!file.exists()){
           file.createNewFile();
    }