随笔 - 547  文章 - 1  评论 - 295  阅读 - 33万

Java扫描文件目录大小及递归扫描

复制代码
#Java扫描文件目录大小及递归扫描
package com.example.core.mydemo;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileDirSizeTest {
    public static void main(String[] args) {
        try{
            FileWriter fw  = new FileWriter("E:\\test\\test221109.txt");
            printDir("E:\\test",fw);
            fw.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void printDir(String dir,FileWriter fw) throws IOException {
        File f = new File(dir);
        if(f.exists()){
            File[] fileArray = f.listFiles();
            for(File f2 : fileArray){
                if(f2.isDirectory()){
                    long size = FileUtils.sizeOfDirectory(new File(f2.getPath()));
                    String realSize = "0";
                    if (size>FileUtils.ONE_GB) {
                        realSize = String.valueOf((size / FileUtils.ONE_GB))+"GB";
                    }else if(size >=FileUtils.ONE_MB){
                        realSize = String.valueOf((size / FileUtils.ONE_MB))+"MB";
                    }else if(size >=FileUtils.ONE_KB){
                        realSize = String.valueOf((size / FileUtils.ONE_KB))+"KB";
                    }
                    System.out.println("Path:"+f2.getAbsolutePath()+",Size: " + realSize);
                    fw.write("Path:"+f2.getAbsolutePath()+",Size: " + realSize +"\n");
                    printDir(f2.getAbsolutePath(),fw);
                }
            }

        }
    }


}
复制代码

 

posted on   oktokeep  阅读(282)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示