What is FileUtils.sizeOfAsBigInteger() in Java?

sizeOfAsBigInteger() is a static methodthe methods in Java that can be called without creating an object of the class. of FileUtils that is used to get the size of a specified file or directory in bytes.

  • The file’s length is returned if the provided file is a regular file.

  • The size of the directory is calculated recursively if the argument is a directory.

  • If a directory or subdirectory is security restricted, its size will not be included.

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 BigInteger sizeOfAsBigInteger(final File file)

Parameters

  • final File file: The file/directory to calculate the size of.

Return value

This method returns the length of the file or recursive size of the directory in bytes.

Code

main.java
1.txt
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.sizeOfAsBigInteger(%s) is - %s", filePath,FileUtils.sizeOfAsBigInteger(file));
System.out.println();
filePath = "1.txt";
file = new File(filePath);
System.out.printf("The output of FileUtils.sizeOfAsBigInteger(%s) is - %s", filePath,FileUtils.sizeOfAsBigInteger(file));
}
}

Output

The output of the code will be as follows.

The output of FileUtils.sizeOf(/Users/educative/Downloads) is - 55464744799
The output of FileUtils.sizeOf(1.txt) is - 15

Example 1

  • directory file path - "/Users/educative/Downloads"

The method returns the value 55464744799 indicating the size of the Downloads directory in bytes.

Example 2

  • directory file path - "1.txt"

The method returns the value 15 indicating the length of the file in bytes.

Free Resources