FileNotFoundException (permission denied) when trying to write a file to an SD card in Android

As you can see from the name, I had a problem writing a file to an SDCard in Android. I checked this question , but it did not help me. I want to write a file that will be in open space on an SD card so that any other application can read it.

Firstly, I check if sdcard is installed:

Environment.getExternalStorageState(); 

Then I ran this code:

 File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); baseDir.mkdirs(); File file = new File(baseDir, "file.txt"); try { FileOutputStream out = new FileOutputStream(file); out.flush(); out.close(); Log.d("NEWFILE", file.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } 

I have:

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

in my AndroidManifest.xml.

Exact error:

 java.io.FileNotFoundException: /storage/1510-2908/Download/secondFile.txt: open failed: EACCES (Permission denied) 

I am testing my code on an emulator (Nexus5 API 23 emulation). The minimum required SDK version is 19 (4.4 Kitkat).


In addition, everything works fine with writing files to a private folder on an SD card with the same code, so I would say that the previous code should work too:

 File newFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "esrxdtcfvzguhbjnk.txt"); newFile.getParentFile().mkdirs(); try { FileOutputStream out = new FileOutputStream(newFile); out.flush(); out.close(); Log.d("NEWFILE", newFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } 

Does anyone know what could be the problem? Maybe something KitKat 4.4 just doesn’t allow you to write to open space in sdcard or?

+7
java android android-permissions filenotfoundexception
source share
1 answer
  • Everything works fine with writing files to a private folder on sdcard

Starting with Android 4.4, these permissions are not required if you are reading or writing only files that are private to your application. For more information, see saving files that are closed to the application.

  1. FileNotFoundException (permission denied) when trying to write a file to an SD card in Android

Since you are trying to write a file in an emulator with API 23 (Marshmallow), you also need to request WRITE_EXTERNAL_STORAGE permission at run time. See and for details.

+16
source share

All Articles