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 returns 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 byte. If you want a more human-readable size you can utilize the FileUtils.byteCountToDisplaySize() method, it will convert the byte value into something like 1 MB, 1 GB.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.math.BigInteger;

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

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

The result of the code snippet above:

TempDir size = 514239345 bytes
TempDir size = 490 MB
DropboxDir size = 6184
DropboxDir size = 6 KB

Maven Dependencies

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

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.