How to Calculate Folder Size in Java
Calculating the size of a folder or directory is trivial. In Java you can recursively traverse each folder and calculate the size of each file individually, and return the sum of all the files. You’ll have to take into account that folders can contain symbolic links and some directories can have zero files.
Calculating the size of a directory – Java
The first and most basic solution is to recursively traverse every folder and add the sum of each file. Finally, return the total length of each directory. Note: for simplicity we kept this example short. Meaning: this example doesn’t take symbolic links into account.
private long getFolderSize(File folder) {
long length = 0;
File[] files = folder.listFiles();
if (files == null || files.length == 0){
return length;
}
for (File file : files) {
if (file.isFile()) {
length += file.length();
} else {
length += getFolderSize(file);
}
}
return length;
}
We can test our method getFolderSize() as in the following example:
@Test
public void testGetFolderSize_Java() throws IOException {
long expectedSize = 76;
File folder = new File("src/test/resources");
long size = getFolderSize(folder);
assertEquals(expectedSize, size);
}
Calculating the size of a directory – Apache Commons IO
Apache Commons IO is a great library which has convenient I/O utilities. We can use this library to calculate the size of a directory. This is a tried and tested library. This already includes good error handling, and takes symbolic links into account.
When you use maven, you could add the library using the following dependency.
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
In the following example, we simply use FileUtils.sizeOfDirectory()
to get the folder size:
@Test
public void testGetFolderSize_ApacheCommonsIo(){
long expectedSize = 76;
File folder = new File("src/test/resources");
long size = FileUtils.sizeOfDirectory(folder);
assertEquals(expectedSize, size);
}
Hmm, you use recursion. It is not use for large Directory tree. Better is implement SimpleFileVisitor from Java.nio
This is one of the most clever solutions to this problem that I’ve seen. I implemented this and tested accuracy for folders up to 20GB–100% correct in each case. I haven’t had the opportunity to test larger data sets.
Thanks again!