问题

这个问题在这里已有答案:

  • 如何在java中将字节大小转换为人类可读的格式? 19个答案

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

例如

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

等等

我发现this previous answer,我觉得不太满意

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

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

那么,有两种可能性:

  • 我更喜欢公共图书馆中的一个开箱即用的解决方案,如apache commons或google guava。
  • 如果没有,有人可以告诉我如何摆脱'.0'部分(不使用字符串替换和正则表达式,我可以自己做)

#1 热门回答(333 赞)

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 ....而且程序很短!


#2 热门回答(7 赞)

你可能会有更多运气java.text.DecimalFormat。这段代码可能应该这样做(尽管......但是......)
new DecimalFormat("#,##0.#").format(value) + " " + unit


#3 热门回答(2 赞)

令我惊讶的是,基于循环的算法速度提高了约10%。

public static String toNumInUnits(long bytes) {
    int u = 0;
    for (;bytes > 1024*1024; bytes >>= 10) {
        u++;
    }
    if (bytes > 1024)
        u++;
    return String.format("%.1f %cB", bytes/1024f, " kMGTPE".charAt(u));
}

原文链接