将文件大小格式化为MB,GB等 [英] Format file size as MB, GB, etc

查看:83
本文介绍了将文件大小格式化为MB,GB等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用合理的单位将文件大小显示为 string .

I need to display a file size as a string using sensible units.

例如,

1L ==> "1 B";
1024L ==> "1 KB";
2537253L ==> "2.3 MB"

我找到了此先前的答案,但我感到不满意

I found this previous answer, which I didn't find satisfactory.

我想出了自己的解决方案,它也有类似的缺点:

I have come up with my own solution which has similar shortcomings:

private static final long K = 1024;
private static final long M = K * K;
private static final long G = M * K;
private static final long T = G * K;

public static String convertToStringRepresentation(final long value){
    final long[] dividers = new long[] { T, G, M, K, 1 };
    final String[] units = new String[] { "TB", "GB", "MB", "KB", "B" };
    if(value < 1)
        throw new IllegalArgumentException("Invalid file size: " + value);
    String result = null;
    for(int i = 0; i < dividers.length; i++){
        final long divider = dividers[i];
        if(value >= divider){
            result = format(value, divider, units[i]);
            break;
        }
    }
    return result;
}

private static String format(final long value,
    final long divider,
    final String unit){
    final double result =
        divider > 1 ? (double) value / (double) divider : (double) value;
    return String.format("%.1f %s", Double.valueOf(result), unit);
}

主要问题是我对Decimalformat和/或String.format的了解有限.我希望1024L,1025L等映射到1 KB而不是1.0 KB.

The main problem is my limited knowledge of Decimalformat and / or String.format. I would like 1024L, 1025L, etc. to map to 1 KB rather than 1.0 KB.

因此,有两种可能性:

  1. 我希望在 Apache Commons Google番石榴.
  2. 如果没有,我如何摆脱".0"部分(无需借助字符串替换和正则表达式,我自己可以做到这一点)?

推荐答案

public static String readableFileSize(long size) {
    if(size <= 0) return "0";
    final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

这将达到1000 TB的容量....而且程序很短!

This will work up to 1000 TB.... and the program is short!

这篇关于将文件大小格式化为MB,GB等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆