sizeOfDirectoryAsBigInteger()
is a FileUtils
class that is used to get the size of a directory recursively in bytes.
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;
public static BigInteger sizeOfDirectoryAsBigInteger(final File directory)
final File directory
: This is the directory to get the size.This method returns the size of the directory in bytes.
import org.apache.commons.io.FileUtils;import java.io.File;public class Main{public static void main(String[] args){String filePath = "/Users/educative/Downloads";File file = new File(filePath);System.out.printf("The output of FileUtils.sizeOfDirectoryAsBigInteger(%s) is - %s", filePath,FileUtils.sizeOfDirectoryAsBigInteger(file));System.out.println();filePath = "1.txt";file = new File(filePath);System.out.printf("The output of FileUtils.sizeOfDirectoryAsBigInteger(%s) is - %s", filePath,FileUtils.sizeOfDirectoryAsBigInteger(file));}}
"/Users/educative/Downloads"
The method returns the value 55464744799
, indicating the size of the directory (supplied as the argument) in bytes.
"1.txt"
The method throws an IllegalArgumentException
, indicating that the file is not a directory.
The output of the code will be as follows:
The output of FileUtils.sizeOfDirectoryAsBigInteger(/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.sizeOfDirectoryAsBigInteger(FileUtils.java:2928)
at Main.main(Main.java:15)