Convert Byte Size to Human-Readable Format in Java
Problem:
Converting byte size into a human-readable format, such as "1 Kb" or "1 Mb," is a common requirement. Instead of manually writing this utility in each project, exploring existing libraries for such functionality is desirable.
Solution:
Apache Commons
Apache Commons provides two static methods for converting byte size to a human-readable format:
Implementation:
public static String humanReadableByteCountSI(long bytes) { // ... code from Apache Commons } public static String humanReadableByteCountBin(long bytes) { // ... code from Apache Commons }
Example:
System.out.println(humanReadableByteCountSI(1024)); // output: "1.0 kB" System.out.println(humanReadableByteCountBin(1024)); // output: "1.0 KiB"
The above is the detailed content of How Can I Convert Bytes to Human-Readable Format in Java?. For more information, please follow other related articles on the PHP Chinese website!