java 删除多层文件夹

 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  

 

posted @ 2019-03-14 17:19  热爱于丫丫  阅读(1443)  评论(0编辑  收藏  举报