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 of org.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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button