Last Updated: September 12, 2021
·
33.12K
· Bruno Volpato

Formatting byte size to human readable format in Java

// From https://programming.guide/java/formatting-byte-size-to-human-readable-format.html

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());

}