sajjoo sajjoo - 5 months ago 26
Android Question

Creating a directory in /sdcard fails

I have been trying to create a directory in

programmatically, but it's not working. The code below always outputs
directory not created.

boolean success = (new File("/sdcard/map")).mkdir();
if (!success) {
Log.i("directory not created", "directory not created");
} else {
Log.i("directory created", "directory created");


There are three things to consider here:

  1. Don't assume that the sd card is mounted at /sdcard (May be true in the default case, but better not to hard code.). You can get the location of sdcard by querying the system:

  2. You have to inform Android that your application needs to write to external storage by adding a uses-permission entry in the AndroidManifest.xml file:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  3. If this directory already exists, then mkdir is going to return false. So check for the existence of the directory, and then try creating it if it does not exist. In your component, use something like:

    File folder = new File(Environment.getExternalStorageDirectory() + "/map");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdir();
    if (success) {
        // Do something on success
    } else {
        // Do something else on failure