轉載自:http://www.cnblogs.com/eczhou/archive/2012/01/16/2323431.htmlhtml
功能:刪除某個目錄及目錄下的全部子目錄和文件java
知識點:File.delete()用於刪除「某個文件或者空目錄」!因此要刪除某個目錄及其中的全部文件和子目錄,要進行遞歸刪除,具體代碼示例以下:測試
import java.io.File;
public class DeleteDirectory {
/**
* 刪除空目錄
* @param dir 將要刪除的目錄路徑
*/
private static void doDeleteEmptyDir(String dir) {
boolean success = (new File(dir)).delete();
if (success) {
System.out.println("Successfully deleted empty directory: " + dir);
} else {
System.out.println("Failed to delete empty directory: " + dir);
}
}
/**
* 遞歸刪除目錄下的全部文件及子目錄下全部文件
* @param dir 將要刪除的文件目錄
* @return boolean Returns "true" if all deletions were successful.
* If a deletion fails, the method stops attempting to
* delete and returns "false".
*/
private 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();
}
/**
*測試
*/
public static void main(String[] args) {
doDeleteEmptyDir("new_dir1");
String newDir2 = "new_dir2";
boolean success = deleteDir(new File(newDir2));
if (success) {
System.out.println("Successfully deleted populated directory: " + newDir2);
} else {
System.out.println("Failed to delete populated directory: " + newDir2);
}
}
}spa