1 /** 2 * 因為不小心,寫了一個死循環,在電腦里創建的了n多層空文件夾 3 * 並且手動最外層刪除不掉. 4 * 所以用寫了本代碼,從里向外的進行刪除操作. 5 * @author Singularity 6 * @since 2019.1.21 7 */ 8 public class Dele { 9 //文件夾所嵌套的層數 10 public static int totalSize; 11 //計數器 12 public static int count; 13 //每次刪除的數量 是100 14 public static int num = 0; 15 //每次刪除的數量 是100 16 public static boolean first = true; 17 18 public static void main(String[] args) { 19 File file = new File("E:\\111"); 20 try { 21 long firstTime = System.currentTimeMillis(); 22 while (true) { 23 //初始化計數器 24 count = 0; 25 totalSize = totalSize - 199; 26 //開始執行刪除操作 27 delAll(file); 28 if (totalSize < 1) { 29 break; 30 } 31 } 32 long okTime = System.currentTimeMillis(); 33 System.out.println("總共耗時:" + ((okTime - firstTime) / 1000) + "秒"); 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } 37 } 38 39 /** 40 * 刪除文件夾下所有內容,包括此文件夾刪除文件夾下所有內容,包括此文件夾 41 * @param f 42 * @throws IOException 43 */ 44 public static void delAll(File f) throws IOException { 45 File[] sub = f.listFiles(); 46 //如果是第一次進來 47 if (first) { 48 if (sub != null && sub.length > 0) { 49 count++; 50 delAll(sub[0]); 51 } else { 52 totalSize = count; 53 first = false; 54 System.out.println("===總共有" + totalSize + "層文件夾==="); 55 } 56 //及時清空,否則會出現棧內存溢出StackOverflowError 57 sub = null; 58 } else { 59 if (sub.length > 0) { 60 count++; 61 if (totalSize - count < 100) { 62 FileUtils.deleteDirectory(f); 63 System.out.println(">>>還有" + (count - 1) + "層文件夾沒有刪除"); 64 }else { 65 delAll(sub[0]); 66 } 67 } 68 //及時清空,否則會出現堆內存溢出 69 sub = null; 70 } 71 } 72 } 73