android - How to create directory automatically on SD card

ID : 20194

viewed : 21

Tags : androidandroid-fileandroid

Top 5 Answer for android - How to create directory automatically on SD card

vote vote


If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:

// create a File object for the parent directory File wallpaperDirectory = new File("/sdcard/Wallpaper/"); // have the object build the directory structure, if needed. wallpaperDirectory.mkdirs(); // create a File object for the output file File outputFile = new File(wallpaperDirectory, filename); // now attach the OutputStream to the file object, instead of a String representation FileOutputStream fos = new FileOutputStream(outputFile); 

Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.

UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:

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


Had the same problem and just want to add that AndroidManifest.xml also needs this permission:

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


Here is what works for me.

 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"  

in your manifest and the code below

public static boolean createDirIfNotExists(String path) {     boolean ret = true;      File file = new File(Environment.getExternalStorageDirectory(), path);     if (!file.exists()) {         if (!file.mkdirs()) {             Log.e("TravellerLog :: ", "Problem creating Image folder");             ret = false;         }     }     return ret; } 
vote vote


Actually I used part of @fiXedd asnwer and it worked for me:

  //Create Folder   File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");   folder.mkdirs();    //Save the path as a string value   String extStorageDirectory = folder.toString();    //Create New file and name it Image2.PNG   File file = new File(extStorageDirectory, "Image2.PNG"); 

Make sure that you are using mkdirs() not mkdir() to create the complete path

vote vote


With API 8 and greater, the location of the SD card has changed. @fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).

You can read more in the SDK documentation.

Top 3 video Explaining android - How to create directory automatically on SD card