文件大小工具类.

本文介绍了一个用于将文件大小转换为易于阅读格式的Java工具类。该工具类支持从字节到PB级别的单位转换,并提供了相应的静态方法来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * <p>
 * 文件大小工具类.
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2013-01-02 12:50 PM
 * @since JDK 1.5
 */
public class FileSizeHelper {

    public static long ONE_KB = 1024;
    public static long ONE_MB = ONE_KB * 1024;
    public static long ONE_GB = ONE_MB * 1024;
    public static long ONE_TB = ONE_GB * (long)1024;
    public static long ONE_PB = ONE_TB * (long)1024;

    public static String getHumanReadableFileSize(Long fileSize) {
        if(fileSize == null) return null;
        return getHumanReadableFileSize(fileSize.longValue());
    }

    public static String getHumanReadableFileSize(long fileSize) {
        if(fileSize < 0) {
            return String.valueOf(fileSize);
        }
        String result = getHumanReadableFileSize(fileSize, ONE_PB, "PB");
        if(result != null) {
            return result;
        }

        result = getHumanReadableFileSize(fileSize, ONE_TB, "TB");
        if(result != null) {
            return result;
        }
        result = getHumanReadableFileSize(fileSize, ONE_GB, "GB");
        if(result != null) {
            return result;
        }
        result = getHumanReadableFileSize(fileSize, ONE_MB, "MB");
        if(result != null) {
            return result;
        }
        result = getHumanReadableFileSize(fileSize, ONE_KB, "KB");
        if(result != null) {
            return result;
        }
        return String.valueOf(fileSize)+"B";
    }

    private static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {
        if(fileSize == 0) return "0";

        if(fileSize / unit >= 1) {
            double value = fileSize / (double)unit;
            DecimalFormat df = new DecimalFormat("######.##"+unitName);
            return df.format(value);
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值