Converting byte sizes into human-readable formats, such as "1 kB" or "1 MB," is a common task in Java programming. While you may often write your own utility methods for this, there are also reusable solutions available.
The Apache Commons Lang library provides static methods for converting byte sizes:
Here are the implementations of these methods:
SI Units:
public static String humanReadableByteCountSI(long bytes) { if (-1000 < bytes && bytes < 1000) { return bytes + " B"; } CharacterIterator ci = new StringCharacterIterator("kMGTPE"); while (bytes <= -999_950 || bytes >= 999_950) { bytes /= 1000; ci.next(); } return String.format("%.1f %cB", bytes / 1000.0, ci.current()); }
Binary Units:
public static String humanReadableByteCountBin(long bytes) { long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes); if (absB < 1024) { return bytes + " B"; } long value = absB; CharacterIterator ci = new StringCharacterIterator("KMGTPE"); for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >>> i; i -= 10) { value >>>= 10; ci.next(); } value *= Long.signum(bytes); return String.format("%.1f %ciB", value / 1024.0, ci.current()); }
The following table shows the output for various byte sizes using both SI and Binary methods:
Byte Size | SI | Binary |
---|---|---|
0 | 0 B | 0 B |
27 | 27 B | 27 B |
1024 | 1.0 kB | 1.0 KiB |
1728 | 1.7 kB | 1.7 KiB |
1855425871872 | 1.9 TB | 1.7 TiB |
The above is the detailed content of How to Convert Byte Sizes to Human-Readable Formats in Java?. For more information, please follow other related articles on the PHP Chinese website!