Skip to content Skip to sidebar Skip to footer

Android Mkdirs() Sdcard Do Not Work

I want to make dir in Sdcard, and i do follow: I added: in manifest. I get root_path by: public

Solution 1:

Try like this it will create a folder in the sd card

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello_world");    
myDir.mkdirs();

If you want to check that file exists or not use this code

File file = new File (myDir, file_name);
if (file.exists ()) 
   // file exist 
else 
   // file not exist  

For reference look at this answer Android saving file to external storage


Solution 2:

The error is cause by && in while (!file.isDirectory() && !file.mkdirs()) it should be while (!file.isDirectory() || !file.mkdirs()). You should also check if the media is mounted.

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    {
        if (DEBUG) {Log.d(TAG, "createSoundDir: media mounted");} //$NON-NLS-1$
        File externalStorage = Environment.getExternalStorageDirectory();
        if (externalStorage != null)
        {
            String externalStoragePath = externalStorage.getAbsolutePath();
            File soundPathDir = new File(externalStoragePath + File.separator + "Hello_World"); //$NON-NLS-1$

            if (soundPathDir.isDirectory() || soundPathDir.mkdirs())
            {
                String soundPath = soundPathDir.getAbsolutePath() + File.separator;
                if (DEBUG) {Log.d(TAG, "soundPath = " + soundPath);} //$NON-NLS-1$

            }
        }
    }

Cut and paste from one of my project.


Solution 3:

Thank all you guys, finally i found out the problem. The problem is in the while() loop, I replace by

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && !file.isDirectory()) {
file.mkdirs();
}


Solution 4:

Use Environment.getExternalStorageDirectory().getAbsolutePath() as below...

public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Hello_World/";

And Check that SDCard is mounted before creating directory as below....

File file = new File(Constants.ROOT_PATH);
int i = 0;

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
      if(!file.exists()) {
          file.mkdir();
      }
}

Post a Comment for "Android Mkdirs() Sdcard Do Not Work"