How do I create a human-readable file size?

This example demonstrate how to create a human-readable file size using the FileUtils class of the Apache Commons IO library. The byteCountToDisplaySize() method take the file size in bytes and return a human-readable display of the file size in bytes, kilobytes, megabytes, gigabytes, etc.

package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;

public class ReadableFileSize {
    public static void main(String[] args) {
        File file = new File("/Users/kodejava/Downloads/Java/JDK/jdk-6u7-linux-i586.bin");

        long size = file.length();
        String display = FileUtils.byteCountToDisplaySize(size);

        System.out.println("Name    = " + file.getName());
        System.out.println("Size    = " + size);
        System.out.println("Display = " + display);
    }
}

Here are the result of our program:

Name    = jdk-6u7-linux-i586.bin
Size    = 78482905
Display = 74 MB

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply