What is FileUtils.sizeOf() in Java?

Overview

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

  • If the file provided is a regular file, then the file’s length is returned.
  • If the argument is a directory, then the size of the directory is calculated recursively.
  • If a directory or subdirectory is security-restricted, then its size is not included.
  • The method might return a negative value if the size of the directory causes an overflow. To overcome this problem, use the method FileUtils.sizeOfAsBigInteger().

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

Parameters

  • final File file: This is the file/directory to calculate the size.

Return value

This method returns the length of the file or the 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.sizeOf(%s) is - %s", filePath,FileUtils.sizeOf(file));
System.out.println();
filePath = "1.txt";
file = new File(filePath);
System.out.printf("The output of FileUtils.sizeOf(%s) is - %s", filePath,FileUtils.sizeOf(file));
}
}

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.

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

Free Resources

Attributions:
  1. undefined by undefined