Java - Print file size in human readable form

By xngo on June 30, 2019

import java.text.DecimalFormat;
 
public class HumanReadableFileSize {
    /**
     * Return human readable file size. This function is limited to exabyte.
     * 
     * @param size
     * @return a human-readable display value (includes units - EB, PB, TB, GB, MB,
     *         KB or bytes).
     */
    public static String readableFileSize(long size) {
        if (size <= 1)
            return size + " byte";
 
        final String[] units = new String[] { "bytes", "KB", "MB", "GB", "TB", "PB", "EB" };
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) 
                                                                + " " + units[digitGroups];
    }
 
    public static void main(String[] args) {
        System.out.println(readableFileSize(0)); // 0 byte
        System.out.println(readableFileSize(1)); // 1 byte
        System.out.println(readableFileSize(937)); // 937 bytes
        System.out.println(readableFileSize(1024)); // 1 KB
        System.out.println(readableFileSize(1124)); // 1.1 KB
        System.out.println(readableFileSize(1224 * 1024)); // 1.2 MB
        System.out.println(readableFileSize(1324 * 1024 * 1024)); // 1.29 GB
        System.out.println(readableFileSize(1424L * 1024L * 1024L * 1024L)); // 1.39 TB
        System.out.println(readableFileSize(1524L * 1024L * 1024L * 1024L * 1024L)); // 1.49 PB
        System.out.println(readableFileSize(1624L * 1024L * 1024L * 1024L * 1024L * 1024L)); // 1.59 EB
    }
 
}

Output

0 byte
1 byte
937 bytes
1 KB
1.1 KB
1.2 MB
1.29 GB
1.39 TB
1.49 PB
1.59 EB

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/io/HumanReadableFileSize.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.