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 2022-11-14 13:56  oktokeep  阅读(278)  评论(1编辑  收藏  举报