在Java程序中,如何如何删除一个目录?
以下示例演示如何使用File
类的dir.isDirectory()
,dir.list()
和deleteDir()
方法来删除其文件和子目录后,再删除该目录。
package com.yiibai;
import java.io.File;
public class DeleteDirectory {
public static void main(String[] argv) throws Exception {
String deldir = "F:\\worksp\\javaexamples\\java_directories\\dir1";
deleteDir(new File(deldir));
}
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;
}
}
}
System.out.println("The directory is deleted.");
return dir.delete();
}
}
执行上面示例代码,得到以下结果 -
The directory is deleted.
The directory is deleted.
The directory is deleted.
注:由于dir1目录中有两个目录,所以上面会多打印两条信息。