java统计磁盘文件和文件夹大小

因为公司配置的SSD非常小(仅100G),经常出现磁盘不够用的情况,所以每次都得手动清理垃圾文件。

 

清理倒好,主要是找大的垃圾文件麻烦,清理少了又不够用。

 

so 现在写了个java程序,查看磁盘文件大小,并且按从大到小的顺序列出来。

 

源码如下:

 

 

package com.raycloud.test.tools;

import java.io.File;
import java.util.*;

/**
 *
 * 统计磁盘中文件的大小,并按从大到小排序
 * @Author : tangshengshan@raycloud.com
 * @Date : 2015/4/15 17:08
 * @From : raytest
 */
public class StatsFileSize {

    static long unitGB = 1024*1024*1024;
    static long unitMB = 1024*1024;
    static long unitKB = 1024;

    public static void main(String[] args) {


        File rootFile = new File("d:\\");
File files [] =rootFile.listFiles();
Map<String,Long> map= new HashMap<String, Long>();
        for(File file : files){
            long len = 0;
            if(file.isDirectory()){
                len = getDirFileLen(file.getPath());
}else{
                len = file.length();
}
            map.put(file.getName(), len);
}

        //排序
Set<Map.Entry<String,Long>> entrySet = map.entrySet();
List<Map.Entry<String,Long>> list = new ArrayList<Map.Entry<String, Long>>();
        for(Map.Entry<String,Long> entry : entrySet){
            list.add(entry);
}
        Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
            @Override public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
                return o2.getValue().compareTo(o1.getValue());
}
        });

        for(Map.Entry<String,Long> entry : list){
            //len trans for hman
long len = entry.getValue();
String strLen = "";
            if(len > unitGB){
                strLen = len / unitGB +"GB";
}else if(len > unitMB){
                strLen = len / unitMB +"MB";
}else if(len > unitKB){
                strLen = len / unitKB +"KB";
}else{
                strLen = len +"B";
}
            System.out.println(entry.getKey()+"  "+strLen);
}

    }

    /**
     * 获得文件夹长度
     * @param filePath
* @return
     */
public static long getDirFileLen(String filePath){
        File rootFile = new File(filePath);
        long resultLen = 0;
File files [] =rootFile.listFiles();
        if(files == null){
            return resultLen;
}
        for(File file : files){
            if(!file.isDirectory()){  //dir
resultLen += file.length();
}else{  //file
resultLen+=getDirFileLen(file.getPath());
}
        }
        return resultLen;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值