一尘不染

如何在Java中将字节大小转换成可读格式?

java

如何在Java中将字节大小转换为人类可读的格式?像1024应该变成“ 1 Kb”,而1024 * 1024应该变成“ 1 Mb”。

我有点讨厌为每个项目编写此实用程序方法。Apache Commons中是否为此有任何静态方法?


阅读 743

收藏
2020-03-06

共1个答案

一尘不染

SI(1 k = 1,000)

public static String humanReadableByteCountSI(long bytes) {
    String s = bytes < 0 ? "-" : "";
    long b = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
    return b < 1000L ? bytes + " B"
            : b < 999_950L ? String.format("%s%.1f kB", s, b / 1e3)
            : (b /= 1000) < 999_950L ? String.format("%s%.1f MB", s, b / 1e3)
            : (b /= 1000) < 999_950L ? String.format("%s%.1f GB", s, b / 1e3)
            : (b /= 1000) < 999_950L ? String.format("%s%.1f TB", s, b / 1e3)
            : (b /= 1000) < 999_950L ? String.format("%s%.1f PB", s, b / 1e3)
            : String.format("%s%.1f EB", s, b / 1e6);
}

二进制(1 K = 1,024)

public static String humanReadableByteCountBin(long bytes) {
    long b = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
    return b < 1024L ? bytes + " B"
            : b <= 0xfffccccccccccccL >> 40 ? String.format("%.1f KiB", bytes / 0x1p10)
            : b <= 0xfffccccccccccccL >> 30 ? String.format("%.1f MiB", bytes / 0x1p20)
            : b <= 0xfffccccccccccccL >> 20 ? String.format("%.1f GiB", bytes / 0x1p30)
            : b <= 0xfffccccccccccccL >> 10 ? String.format("%.1f TiB", bytes / 0x1p40)
            : b <= 0xfffccccccccccccL ? String.format("%.1f PiB", (bytes >> 10) / 0x1p40)
            : String.format("%.1f EiB", (bytes >> 20) / 0x1p40);

}

输出示例:

                              SI     BINARY

                   0:        0 B        0 B
                  27:       27 B       27 B
                 999:      999 B      999 B
                1000:     1.0 kB     1000 B
                1023:     1.0 kB     1023 B
                1024:     1.0 kB    1.0 KiB
                1728:     1.7 kB    1.7 KiB
              110592:   110.6 kB  108.0 KiB
             7077888:     7.1 MB    6.8 MiB
           452984832:   453.0 MB  432.0 MiB
         28991029248:    29.0 GB   27.0 GiB
       1855425871872:     1.9 TB    1.7 TiB
 9223372036854775807:     9.2 EB    8.0 EiB   (Long.MAX_VALUE)
2020-03-06