How do I calculate directory size?

In this example we are going to use the Apache Commons IO library to get or calculate the total size of a directory. The FileUtils class provided by the Commons IO can help us to achieve this goal.

The first method that we can use is the FileUtils.sizeOfDirectory(), it calculates the size of a directory recursively. It takes a File object that represent a directory as parameter and returns long value. If the directory has security restriction this method return 0. A negative value returned when the directory size if bigger than Long.MAX_VALUE.

You can also use the FileUtils.sizeOfDirectoryAsBigInteger() method. This method return the result as BigInteger as the method name describe. As the first method, this method also return 0 when the directory has a security restriction.

Both of the methods described above return the directory size in bytes. If you want a more human readable size you can utilize the FileUtils.byteCountToDisplaySize() method, it will convert the bytes value into something like 1 MB, 1 GB.



import java.math.BigInteger;

public class DirectorySizeSample {
    public static void main(String[] args) {
        // sizeOfDirectory
        File tempDir = new File("/Users/wsaryada/Temp");
        long size = FileUtils.sizeOfDirectory(tempDir);
        System.out.println("TempDir size = " + size + " bytes");
        System.out.println("TempDir size = " +

        // sizeOfDirectoryAsBigInteger()
        File dropboxDir = new File("/Users/wsaryada/Dropbox");
        BigInteger sizeBig = FileUtils.sizeOfDirectoryAsBigInteger(dropboxDir);
        System.out.println("DropboxDir size = " + sizeBig);
        System.out.println("DropboxDir size = " +

The result of the code snippet above:

TempDir size = 51054594 bytes
TempDir size = 48 MB
DropboxDir size = 1244098841
DropboxDir size = 1 GB

Maven Dependencies


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