JAVA精确计算文件大小工具类

  • Post author:
  • Post category:java


package com.link.lfs.base.util;

import java.math.BigDecimal;

public class ByteConverterUtil {
    private static String [] unitStr = new String[]{"B","KB","MB","GB","TB","PB","EB","ZB","YB","BB","NB","DB","CB","XB"};
    /**
     * 精确计算文件大小
     * @param size 字节数
     * @param decimalPlaces 保留小数点后N位
     * @param unit 字节转换指定单位(无法转换低于1的单位,如0.9M将会以KB响应)
     * @return
     */
    public static String getPrintSize(long size,int decimalPlaces,String unit) {
        String result = size + "B";
        BigDecimal bd = new BigDecimal(String.valueOf(size));
        BigDecimal bd1024 = new BigDecimal("1024");
        for (int i = 0; i < unitStr.length; i++) {
            if(unitStr[i].equals(unit)){
                if(decimalPlaces < 1){
                    result = bd.toString() + unitStr[i];
                }else {
                    result = bd.setScale(decimalPlaces,BigDecimal.ROUND_HALF_DOWN).toString() + unitStr[i];
                }
                break;
            }
            if(bd.compareTo(bd1024) == -1){
                if(decimalPlaces < 1){
                    result = bd.toString() + unitStr[i];
                }else {
                    result = bd.setScale(decimalPlaces,BigDecimal.ROUND_HALF_DOWN).toString() + unitStr[i];
                }
                break;
            }else{
                bd = bd.divide(bd1024);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(getPrintSize(12,0,"MB"));
        System.out.println(getPrintSize(1562,3,"B"));
        System.out.println(getPrintSize(15623,2,null));
        System.out.println(getPrintSize(1562003,2,null));
        System.out.println(getPrintSize(15620003,2,null));
        System.out.println(getPrintSize(1562300098,5,"MB"));
        System.out.println(getPrintSize(1562300098000000099l,5,null));
    }
}

//欢迎指出可优化部分,共同探讨,共同前进



版权声明:本文为qq_41267876原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。