Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

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

I want to create a new directory inside the SD card programmatically and I want to delete that directory also. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...