Get Readable File Size from Number of Bytes in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO

In this Java tutorial we learn how to use the FileUtils class of Apache Commons IO library to get the human readable file size of a given file size in number of bytes value.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to get Human Readable File Size using FileUtils class

The Apache Commons IO library provides the utility method FileUtils.byteCountToDisplaySize() to get the readable file size in String value with a given number of bytes. The method can work with the number of bytes argument in long or BigInteger data type as the example Java program below.

ReadableFileSize.java

import org.apache.commons.io.FileUtils;

import java.math.BigInteger;

public class ReadableFileSize {
    public static void main(String... args) {
        long fileSizeInBytes1 = 50000;
        long fileSizeInBytes2 = 100000000;
        BigInteger fileSizeInBytes3 = new BigInteger("555500000999");
        BigInteger fileSizeInBytes4 = new BigInteger("9876543219876");

        String fileSizeDisplay1 = FileUtils.byteCountToDisplaySize(fileSizeInBytes1);
        String fileSizeDisplay2 = FileUtils.byteCountToDisplaySize(fileSizeInBytes2);
        String fileSizeDisplay3 = FileUtils.byteCountToDisplaySize(fileSizeInBytes3);
        String fileSizeDisplay4 = FileUtils.byteCountToDisplaySize(fileSizeInBytes4);

        System.out.println(fileSizeDisplay1);
        System.out.println(fileSizeDisplay2);
        System.out.println(fileSizeDisplay3);
        System.out.println(fileSizeDisplay4);
    }
}
The output is:
48 KB
95 MB
517 GB
8 TB

Happy Coding 😊