What is FileUtils.sizeOfDirectory() in Java?

Overview

sizeOfDirectory() is a staticthe methods in Java that can be called without creating an object of the class method of the FileUtils class that is used to recursively get the size of a directory in bytes.

The method may return a negative value if the size of the directory causes an overflow. To overcome this problem, use the FileUtils.sizeOfDirectoryAsBigInteger() method.

How to import FileUtils

The definition of FileUtils can be found in the Apache Commons IO package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


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

For other versions of the commons-io package, refer to the Maven Repository.

You can import the FileUtils class as follows:


import org.apache.commons.io.FileUtils;

Syntax


public static long sizeOfDirectory(File directory)

Parameters

  • directory: The directory whose size is to be determined.

Return value

This method returns the size of the directory in bytes.

The return value is a negative number when the size is greater than Long.MAX_VALUE.

The return value is 0 if the directory is restricted due to security concerns.

Code

import org.apache.commons.io.FileUtils;
import java.io.File;
public class Main{
public static void main(String[] args){
// Example 1
String filePath = "/Users/educative/Downloads";
File file = new File(filePath);
System.out.printf("The output of FileUtils.sizeOfDirectory(%s) is - %s", filePath,FileUtils.sizeOfDirectory(file));
System.out.println();
// Example 2
filePath = "1.txt";
file = new File(filePath);
System.out.printf("The output of FileUtils.sizeOfDirectory(%s) is - %s", filePath,FileUtils.sizeOfDirectory(file));
}
}

Output

The output of the code is as follows:


The output of FileUtils.sizeOfDirectory(/Users/educative/Downloads) is - 55464744799


Exception in thread "main" java.lang.IllegalArgumentException: Parameter 'directory' is not a directory: '1.txt'
	at org.apache.commons.io.FileUtils.requireDirectory(FileUtils.java:2635)
	at org.apache.commons.io.FileUtils.requireDirectoryExists(FileUtils.java:2651)
	at org.apache.commons.io.FileUtils.sizeOfDirectory(FileUtils.java:2889)
	at Main.main(Main.java:15)

Explanation

Example 1

  • filePath = "/Users/educative/Downloads"

The method returns the value 55464744799, which indicates the size of the directory in bytes.

Example 2

  • filePath - "2.txt"

The method throws an IllegalArgumentException, which indicates that the file is not a directory.

Free Resources

Attributions:
  1. undefined by undefined