Java File IO - Calculate total files, sub directories and size of a directory
- Details
- Written by Nam Ha Minh
- Last Updated on 27 July 2019   |   Print Email
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:
- How to clean and remove a non-empty directory in Java
- How to copy a directory programmatically in Java
- List files and directories recursively in a directory in Java
- How to rename/move file or directory in Java
Other Java File IO Tutorials:
- How to Read and Write Text File in Java
- How to Read and Write Binary Files in Java
- Java IO - Common File and Directory Operations Examples
- Java Serialization Basic Example
- Understanding Java Externalization with Examples
- How to compress files in ZIP format in Java
- How to extract ZIP file in Java
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments