io
Get directory size
In this example we shall show you how to get the size of a directory. We are using the org.apache.commons.io.FileUtils
class that provides general file manipulation utilities. To get the size of a directory one should perform the following steps:
- Create a String with the path to the directory.
- Create a new File instance by converting the given pathname string into an abstract pathname.
- Use the
sizeOfDirectory(File directory)
method oforg.apache.commons.io.FileUtils
class. It counts the size of the directory recursively (it counts the sum of the length of all files),
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.io.File; import org.apache.commons.io.FileUtils; public class GetDirectorySize { public static void main(String[] args) { // Set a string with the path of the directory String directory = "C:/Program Files"; // Get the size of the folder long size = FileUtils.sizeOfDirectory(new File(directory)); // Print the result System.out.println("The size of directory " + directory + " is " + size + " bytes"); } }
Output:
The size of directory C:/Program Files is 4073913382 bytes
This was an example of how to get the size of a directory in Java.