In this Java File IO article, I will guide you how to write Java code to calculate the total number of files, sub directories and size of a given directory. The main principles for implementing such method are recursion algorithm and accumulation of the calculated numbers after each iteration. Here’s the code of such utility method:

public static long[] calculateDirectoryInfo(String dirPath) {
	long[] result = new long[] {0, 0, 0};
	int totalFiles = 0;
	int totalDirs = 0;
	long totalSize = 0;

	File dir = new File(dirPath);

	if (!dir.exists()) {
		throw new IllegalArgumentException("The given path does not exist.");
	}

	if (dir.isFile()) {
		throw new IllegalArgumentException("The given path is a file. A directory is expected.");
	}

	File[] subFiles = dir.listFiles();

	if (subFiles != null && subFiles.length > 0) {
		for (File aFile : subFiles) {
			if (aFile.isFile()) {
				totalFiles++;
				totalSize += aFile.length();
			} else {
				totalDirs++;
				long[] info = calculateDirectoryInfo(aFile.getAbsolutePath());
				totalDirs += info[0];
				totalFiles += info[1];
				totalSize += info[2];
			}
		}

		result[0] = totalDirs;
		result[1] = totalFiles;
		result[2] = totalSize;
	}

	return result;
}

As we can see, this method takes a String which is path of the directory and returns an array of long numbers in which:

    • The 1st number is the total sub directories.
    • The 2nd number is the total files.
    • The 3rd number is the total size (in bytes).

And the following code snippet illustrates how to use the above method:

String dirPath = "E:/Test/Upload";

long[] dirInfo = calculateDirectoryInfo(dirPath);

System.out.println("Total sub directories: " + dirInfo[0]);
System.out.println("Total files: " + dirInfo[1]);
System.out.println("Total size: " + dirInfo[2]);

Example Output:

Total sub directories: 15
Total files: 33
Total size: 37156661 

 

Related File IO Tutorials:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (DirectoryCalculationExample.java)DirectoryCalculationExample.java[Example program]1 kB

Add comment

   


Comments 

#1Ding2021-06-15 09:05
Such an elegant program, amazing! Thanks!
Quote