Java中删除文件、删除目录及目录下所有文件
生活随笔
收集整理的這篇文章主要介紹了
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中删除文件、删除目录及目录下所有文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中生成不重复随机的数字
- 下一篇: Java Math的 floor,rou