Search code examples
androidmkdirs

Android mkdirs() sdcard do not work


I want to make dir in Sdcard, and i do follow:

  1. I added: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in manifest.
  2. I get root_path by: public static final String ROOT_PATH = Environment.getExternalStorageDirectory().toString() + "/Hello_World/"; and it returns /storage/emulated/0/Hello_World (getting when debug).

Next, I run this code:

File file = new File(Constants.ROOT_PATH);
int i = 0;
while (!file.isDirectory() && !file.mkdirs()) {
    file.mkdirs();
    Log.e("mkdirs", "" + i++);
}

I also tried both mkdirs() and mkdir() but it's showing endless loop in logcat (Log.e("mkdirs", "" + i++);). Sometimes it work, but sometimes not. Thanks for you helping!
Update: I tried my code for some devices: Nexus4, nexus7, Vega Iron, Genymotion, LG G Pro, then just Vega Iron work as expected. ??!!?!?


Solution

  • 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