Dir Size
## Java Program to Get Directory Size
In Java, calculating the size of a directory is not as straightforward as calling a single method on a standard `java.io.File` object, because `File.length()` only returns the size of the directory file itself (which contains metadata), not the cumulative size of its contents.
To get the actual size of a directory, you must recursively sum the sizes of all files within it. This tutorial demonstrates how to achieve this efficiently using both the popular **Apache Commons IO** library and modern **Java NIO (Java 8+)** APIs.
---
## Method 1: Using Apache Commons IO (Recommended)
The easiest and most readable way to get a directory's size is by using the `FileUtils` class from the **Apache Commons IO** library.
### Dependency Setup
If you are using Maven, add the following dependency to your `pom.xml`:
```xml
commons-io
commons-io
2.15.1
```
For Gradle:
```groovy
implementation 'commons-io:commons-io:2.15.1'
```
### Code Example
The `FileUtils.sizeOfDirectory(File directory)` method recursively calculates the size of the specified directory in bytes.
```java
import java.io.File;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) {
// Specify the directory path
File directory = new File("C:/test");
try {
// Calculate size in bytes
long size = FileUtils.sizeOfDirectory(directory);
System.out.println("Size: " + size + " bytes");
// Optional: Display in human-readable format (e.g., KB, MB, GB)
String humanReadableSize = FileUtils.byteCountToDisplaySize(size);
System.out.println("Human-readable size: " + humanReadableSize);
} catch (IllegalArgumentException e) {
System.err.println("The provided path is not a valid directory: " + e.getMessage());
}
}
}
```
### Output
```text
Size: 2048 bytes
Human-readable size: 2 KB
```
---
## Method 2: Using Java NIO (No External Dependencies)
If you prefer not to add external libraries to your project, you can use Java 8's `java.nio.file.Files` API to walk the file tree and sum the file sizes.
### Code Example
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class GetDirSizeNio {
public static void main(String[] args) {
Path path = Paths.get("C:/test");
try (Stream walk = Files.walk(path)) {
long size = walk
.filter(Files::isRegularFile)
.mapToLong(p -> {
try {
return Files.size(p);
} catch (IOException e) {
System.err.printf("Failed to get size of %s: %s%n", p, e.getMessage());
return 0L;
}
})
.sum();
System.out.println("Size: " + size + " bytes");
} catch (IOException e) {
System.err.println("Error accessing directory: " + e.getMessage());
}
}
}
```
---
## Key Considerations
1. **Symbolic Links**: Be cautious when directories contain symbolic links. `FileUtils.sizeOfDirectory()` handles symbolic links by default without following them to prevent infinite loops. If you write custom recursion, ensure you handle symbolic links correctly to avoid `StackOverflowError`.
2. **Permissions**: If your application does not have read permissions for certain subdirectories or files, both methods may throw an `IOException` or security exception.
3. **Performance**: For extremely large directories containing millions of files, calculating the size can be time-consuming and I/O intensive. Consider caching the directory size if real-time accuracy is not critical.
YouTip