sizeOfDirectory()
is a 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.
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 long sizeOfDirectory(File directory)
directory
: The directory whose size is to be determined.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.
import org.apache.commons.io.FileUtils;import java.io.File;public class Main{public static void main(String[] args){// Example 1String 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 2filePath = "1.txt";file = new File(filePath);System.out.printf("The output of FileUtils.sizeOfDirectory(%s) is - %s", filePath,FileUtils.sizeOfDirectory(file));}}
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)
filePath
= "/Users/educative/Downloads"
The method returns the value 55464744799,
which indicates the size of the directory in bytes.
filePath
- "2.txt"
The method throws an IllegalArgumentException
, which indicates that the file is not a directory.
Free Resources