How to convert byte size into human-readable format in Java? Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".
I am kind of sick of writing this utility method for each project. Are there any static methods in Apache Commons for this?
If you use Android, you can simply use Formatter.formatFileSize() .
Alternativey, here's a solution based on this popular post :
Just add more file units (if any missing), and you will see unit size upto that unit (if your file has that much length) System.out.println("File size in proper format: " + bytes + " " + fileSizeUnits[index]); sizeToReturn = String.valueOf(bytes) + " " + fileSizeUnits[index]; return sizeToReturn; }
In the off-chance it saves someone a bit of time, or maybe just for a bit of fun, here's a Go version. For simplicity, I've only included the binary output case.
FileUtils.byteCountToDisplaySize(long size)
would work if your project can depend onorg.apache.commons.io
.JavaDoc for this method
Here is my go at it (no loops and handles both SI units and binary units):
Example output:
Related article: Java: Formatting byte size to human readable format