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

參考:Java中刪除文件、刪除目錄及目錄下所有文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM