How can I convert byte size into a 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. Is there a static method in Apache Commons for this?
To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.
You can convert 512 byte blocks to bytes by multiplying them by 512. For example, six 512-byte-blocks multiplied by 512 equals 3,072 bytes.
The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.
Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
Fun fact: The original snippet posted here was the most copied Java snippet of all time on Stack Overflow, and it was flawed. It was fixed, but it got messy.
Full story in this article: The most copied Stack Overflow snippet of all time is flawed!
Source: Formatting byte size to human readable format | Programming.Guide
public static String humanReadableByteCountSI(long bytes) { if (-1000 < bytes && bytes < 1000) { return bytes + " B"; } CharacterIterator ci = new StringCharacterIterator("kMGTPE"); while (bytes <= -999_950 || bytes >= 999_950) { bytes /= 1000; ci.next(); } return String.format("%.1f %cB", bytes / 1000.0, ci.current()); }
public static String humanReadableByteCountBin(long bytes) { long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes); if (absB < 1024) { return bytes + " B"; } long value = absB; CharacterIterator ci = new StringCharacterIterator("KMGTPE"); for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) { value >>= 10; ci.next(); } value *= Long.signum(bytes); return String.format("%.1f %ciB", value / 1024.0, ci.current()); }
SI BINARY 0: 0 B 0 B 27: 27 B 27 B 999: 999 B 999 B 1000: 1.0 kB 1000 B 1023: 1.0 kB 1023 B 1024: 1.0 kB 1.0 KiB 1728: 1.7 kB 1.7 KiB 110592: 110.6 kB 108.0 KiB 7077888: 7.1 MB 6.8 MiB 452984832: 453.0 MB 432.0 MiB 28991029248: 29.0 GB 27.0 GiB 1855425871872: 1.9 TB 1.7 TiB 9223372036854775807: 9.2 EB 8.0 EiB (Long.MAX_VALUE)
FileUtils.byteCountToDisplaySize(long size)
would work if your project can depend on org.apache.commons.io
.
JavaDoc for this method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With