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.

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("F:/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("F:/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 = 892059058 bytes
TempDir size = 850 MB
DropboxDir size = 892059058
DropboxDir size = 850 MB

Maven Dependencies

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

Leave a Reply

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