Search code examples
androidandroid-studiopermissions

Android studio getting error IOException: Operation not permitted while creating file


I am trying to create a file. (testipfs folder already exists)

File imagesFolder = new File(Environment.getExternalStorageDirectory(), "testipfs");
File photo= new File(imagesFolder, "desktopWallpaper.jpg");
System.out.println("Saving file in "+photo.getAbsolutePath());
if (!photo.exists()) {
   try {
      photo.createNewFile();
   } catch (IOException e) {
      System.out.println("Failed to create photo");
      e.printStackTrace();
   }
}

But getting error Operation not permitted.

I/System.out: Saving file in /storage/emulated/0/testipfs/desktopWallpaper.jpg
I/System.out: Failed to create photo
W/System.err: java.io.IOException: Operation not permitted
W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
        at java.io.File.createNewFile(File.java:1008)
        at com.example.ipfs.MainActivity.SavePhotoTask(MainActivity.java:49)
        at com.example.ipfs.MainActivity.onCreate(MainActivity.java:112)

I have added permission in my manifest file as bellow

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

How do i solve this problem?


Solution

  • I am expecting you are testing your application in android 11, In Android 11 things changed ... You have to ask for this permission

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

    and in you MainActivity

    if (Build.VERSION.SDK_INT >= 30){
            if (!Environment.isExternalStorageManager()){
                Intent getpermission = new Intent();
                getpermission.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivity(getpermission);
            }
        }
    

    Basically this is just an intent which will take user to setting to give us Permission, and this is necessary in android 11 , If you just asking for READ nd WRITE permission then you application is having just a read-only access to files in the device