How to Convert Byte Size into Human-Readable Format in Java
Converting byte size into a human-readable format is a common task in software development. In Java, there's no built-in method for this, but we can use Apache Commons Lang3 for a handy way to do it.
Apache Commons Lang3 provides two methods for humanizing byte counts:
Here's how to use these methods:
import org.apache.commons.lang3.StringUtils; public class ByteSizeConverter { public static void main(String[] args) { long bytes = 1024 * 1024; // Convert to SI format (e.g., 1 MB) String humanReadableBytesSI = StringUtils.humanReadableByteCountSI(bytes); System.out.println(humanReadableBytesSI); // "1 MB" // Convert to binary format (e.g., 1 MiB) String humanReadableBytesBin = StringUtils.humanReadableByteCountBin(bytes); System.out.println(humanReadableBytesBin); // "1 MiB" } }
These methods provide a convenient way to represent byte sizes in a human-readable format, regardless of whether you prefer SI or binary units.
The above is the detailed content of How Can I Convert Bytes to a Human-Readable Format in Java?. For more information, please follow other related articles on the PHP Chinese website!