Calculating Directory Size in Java
Calculating Directory Size in Java
Overview
To compute the total size of a directory in Java, the process involves navigating through the directory structure and summing up the sizes of all contained files.
Implementation Steps
-
Access the Target Dircetory
import java.io.File; File directory = new File("path/to/directory"); -
Enumerate All Files
File[] entries = directory.listFiles(); -
Aggregate File Sizes
long cumulativeSize = 0L; for (File entry : entries) { cumulativeSize += entry.length(); } -
Display Total Size
System.out.println("Total size: " + cumulativeSize + " bytes");
Complete Example
import java.io.File;
public class DirectorySizeCounter {
public static void main(String[] args) {
File directory = new File("path/to/directory");
File[] files = directory.listFiles();
long totalBytes = 0L;
if (files != null) {
for (File file : files) {
totalBytes += file.length();
}
}
System.out.println("Directory size: " + totalBytes + " bytes");
}
}
This approach efficiently copmutes the aggregate size of all file within a given directory.