How to create a file in an SDCARD directory

24,303

Solution 1

Try the following example:

if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    //handle case of no SDCARD present
} else {
    String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
    //create folder
    File folder = new File(dir); //folder name
    folder.mkdirs();

    //create file
    File file = new File(dir, "filename.extension");
}

Don't forget to add the permission to your AndroidManifest:

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

Solution 2

The problem is that mkdirs() is called on a File object containing the whole path up to the actual file. It should be called on a File object containing the Path (the directory) and only that. Then you should use another File object to create the actual file.

Solution 3

You should also have to add permission to write to external media. Add following line in the application manifest file, somewhere between <manifest> tags, but not inside <application> tag:

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

Solution 4

Use This:

DocumentFile tempDir = DocumentFile.fromSingleUri(context,targetDirectoryUri);
DocumentFile newDocumentFile = tempDir.createFile(type,name);

"targetDirectoryUri" is uri of the directory you want to put the file into it. This is the only solution! After Api 19 you can not write on SDCard, so you must use DocumentFile instead File. In addition, you must also take SDCard permission. To learn how to do this and get the targetDirectoryUri, please read this.

Share:
24,303
androniennn
Author by

androniennn

Updated on August 13, 2022

Comments

  • androniennn
    androniennn almost 2 years

    I want to create a file(not created) in a directory(not created) in the SDCARD. How doing it ?

    Thank you.

  • androniennn
    androniennn about 13 years
    i think like this i'm creating 2 directories, the proof that i have a fileNotFound exception when trying to copy a file from /data/data... to "myDirectory" :04-11 20:23:57.173: DEBUG/Carburant(16333): /mnt/sdcard/Carburant/alaa.peugeot.settings.dat (Is a directory)
  • androniennn
    androniennn about 13 years
    yes, i added this! but why it's saying that "myFile.example" is a directory ?
  • Sam
    Sam about 11 years
    it will two directory..Write this code :- String path = Environment.getExternalStorageDirectory()+"/dirName/"; File file = new File(path+dirName); if(!file.exists()){ file.getParentFile().mkdirs(); try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
  • App Kart
    App Kart almost 10 years
    It is create folder not file