How can I create a new directory on the SD card programmatically?

mkdir() for

File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abcabcabc"); 
directory.mkdir();


mkdirs() for
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Mani/abcxyz");
    directory.mkdirs();

new File(Environment.getExternalStorageDirectory(), "DirName").mkdirs();

To create a directory you can use the following code:

File dir = new File("path/to/your/directory");
try{
  if(dir.mkdir()) {
     System.out.println("Directory created");
  } else {
     System.out.println("Directory is not created");
  }
}catch(Exception e){
  e.printStackTrace();
}

To delete an empty directory, you can use this code:

boolean success = (new File("your/directory/name")).delete();
if (!success) {
   System.out.println("Deletion failed!");
}

To delete a non-empty directory, you can use this code:

public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

Maybe you also need this permission:

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

This answer is also a good resource:

How to create directory automatically on SD card


to create a directory, you could use

File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName");

if(!myDirectory.exists()) {                                 
  myDirectory.mkdirs();
}

to delete it,

 myDirectory.delete();

dont forget to add permission:

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

Tags:

Android