我怎样才能创建SD卡编程上一个新的目录?目录、SD

2023-09-13 00:14:18 作者:我爱了一个曾经

我想通过程序生成的SD卡内的一个新的目录,我想删除该目录还。我怎样才能做到这一点?

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?

推荐答案

要创建您可以使用下面的code目录:

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();
}

要删除一个空的目录,你可以使用这个code:

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!");
}

要删除一个非空目录,你可以使用这个code:

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对SD卡自动创建目录