How to Convert Byte Size Into a Human-Readable Format in Java
Convert Byte Size Into a Human-Readable Format in Java
As data sizes continue to grow, it becomes increasingly important for developers to be able to make sense of the raw numbers. When it comes to memory, disk space, and other data storage, understanding the numbers is vital. Luckily, with a few lines of code, it’s easy to convert byte size into a more human-readable format.
Converting byte size into human-readable format in Java is incredibly straightforward. All you need to do is use the java.text.DecimalFormat class to format a double containing the amount of bytes into a human-readable form. Here’s an example:
// Create a DecimalFormat object
DecimalFormat df = new DecimalFormat("#.##");
// Get the number of bytes as a double
double bytes = 1234567.89;
// Convert the bytes to a more readable form
String readableFileSize = df.format(bytes / 1048576) + " MB";
In the above example, we create a DecimalFormat
object and specify the pattern. We then get the number of bytes as a double, divide it by 1048576 to convert it to megabytes, and use the format()
method to format it in the specified pattern. The result will be a String containing the file size in megabytes.
It’s also possible to convert byte sizes into other units such as kilobytes or gigabytes. All you have to do is change the number used to divide the byte size. For example, to convert bytes to kilobytes, you would divide by 1024 instead of 1048576.
When you want to convert byte sizes into human-readable format in Java, the process is simple. With a few lines of code, you can easily format a double containing the amount of bytes into a more manageable size.