How to convert byte size into human readable format in java
human readable format
bytes
java
When you need to display informations about files or disk free/used space is useful to convert the bytes size in a human readable format.
Conversion table | ||||
---|---|---|---|---|
Name | Symbol | Binary | Number of bytes | Equal to |
Kilobyte | KB | 210 | 1,024 | 1024 B |
Megabyte | MB | 220 | 1,048,576 | 1024 KB |
Gigabyte | GB | 230 | 1,073,741,824 | 1024 MB |
Terabyte | TB | 240 | 1,099,511,627,776 | 1024 GB |
Petabyte | PB | 250 | 1,125,899,906,842,624 | 1024 TB |
Exabyte | EB | 260 | 1,152,921,504,606,846,976 | 1024 PB |
Zettabyte | ZB | 270 | 1,180,591,620,717,411,303,424 | 1024 EB |
Yottabyte | YB | 280 | 1,208,925,819,614,629,174,706,176 | 1024 ZB |
Example
Here is a simple Java method to convert bytes in human readable format.
package com.admfactory.io;
public class ByteSizeHumanReadable {
/**
* Method to format bytes in human readable format
*
* @param bytes
* - the value in bytes
* @param digits
* - number of decimals to be displayed
* @return human readable format string
*/
public static String format(double bytes, int digits) {
String[] dictionary = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
int index = 0;
for (index = 0; index < dictionary.length; index++) {
if (bytes < 1024) {
break;
}
bytes = bytes / 1024;
}
return String.format("%." + digits + "f", bytes) + " " + dictionary[index];
}
public static void main(String[] args) {
long n1 = 12345678L;
long n2 = 98745678245L;
long n3 = Long.MAX_VALUE;
System.out.println("Test byte human reabable format");
System.out.println();
System.out.println("n1: " + n1 + " ==> 2 decimals: " + format(n1, 2));
System.out.println("n1: " + n1 + " ==> 3 decimals: " + format(n1, 3));
System.out.println();
System.out.println("n2: " + n2 + " ==> 2 decimals: " + format(n2, 2));
System.out.println("n2: " + n2 + " ==> 3 decimals: " + format(n2, 3));
System.out.println();
System.out.println("n3: " + n2 + " ==> 2 decimals: " + format(n3, 2));
System.out.println("n3: " + n2 + " ==> 3 decimals: " + format(n3, 3));
}
}
Output
Test byte human reabable format
n1: 12345678 ==> 2 decimals: 11.77 MB
n1: 12345678 ==> 3 decimals: 11.774 MB
n2: 98745678245 ==> 2 decimals: 91.96 GB
n2: 98745678245 ==> 3 decimals: 91.964 GB
n3: 98745678245 ==> 2 decimals: 8.00 EB
n3: 98745678245 ==> 3 decimals: 8.000 EB