Converting byte size into a human-readable format is a common task that involves expressing values like 1024 bytes as "1 Kb" or 1024 * 1024 bytes as "1 Mb." While it is possible to write separate utility methods for this conversion, it can be tedious. Fortunately, Java provides a versatile way to accomplish this task.
Apache Commons offers methods that facilitate the conversion of byte size to human-readable formats. Among these methods are:
humanReadableByteCountSI(): Uses SI units (1 k = 1,000).
humanReadableByteCountBin(): Uses binary units (1 Ki = 1,024).
These methods accept a long value representing the byte size and return a human-readable string.
import org.apache.commons.lang3.StringUtils; public class ByteSizeConverter { public static String convertByteSizeToHumanReadableSI(long bytes) { return StringUtils.humanReadableByteCount(bytes, false); } public static String convertByteSizeToHumanReadableBinary(long bytes) { return StringUtils.humanReadableByteCount(bytes, true); } }
Using the above methods, the sample outputs for different byte sizes are:
Byte Size (SI) | Byte Size (Binary) |
---|---|
0 | 0 B |
1024 | 1 kB |
1048576 | 1 MiB |
1073741824 | 1 GiB |
1099511627776 | 1 TiB |
9223372036854775807 | 8 EiB |
The methods provided by Apache Commons offer a convenient and efficient way to convert byte sizes to human-readable formats. These methods can be easily integrated into existing Java projects, eliminating the need to write custom code for this common task.
The above is the detailed content of How Can Apache Commons Simplify Byte Size Conversion to Human-Readable Format in Java?. For more information, please follow other related articles on the PHP Chinese website!