How to get size of a directory in Java
In Java, we can use Files.size
to get the size of a file; for the directory or folder size, we need to count the size of a directory recursively (sum of the Files.size
of all files).
This example shows a few common ways to get the size of a directory or folder.
FileVisitor
(Java 7)Files.walk
(Java 8)FileUtils.sizeOfDirectory
(Apache Common IO)- Sum
file.length
of all files. (Legacy IO)
1. Directory Size – FileVisitor (Java 7)
This example uses the FileVisitor
to visit all files from a specified path and sum the size of all files.
// size of directory in bytes
public static long getDirectorySizeJava7(Path path) {
AtomicLong size = new AtomicLong(0);
try {
Files.walkFileTree(path, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
// sum size of all visit file
size.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
System.out.printf("Failed to get size of %s%n%s", file, e);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
System.out.printf("%s", e);
}
return size.get();
}
2. Directory Size – Files.walk (Java 8)
This example uses Java 8 Files.walk
and Stream
to walk a directory recursively and sum the size of all files.
// size of directory in bytes
public static long getDirectorySizeJava8(Path path) {
long size = 0;
// need close Files.walk
try (Stream<Path> walk = Files.walk(path)) {
size = walk
//.peek(System.out::println) // debug
.filter(Files::isRegularFile)
.mapToLong(p -> {
// ugly, can pretty it with an extract method
try {
return Files.size(p);
} catch (IOException e) {
System.out.printf("Failed to get size of %s%n%s", p, e);
return 0L;
}
})
.sum();
} catch (IOException e) {
System.out.printf("IO errors %s", e);
}
return size;
}
3. Directory Size – FileUtils (Apache Common IO)
This example uses the Apache Common IO FileUtils.sizeOfDirectory
to get the size of a directory.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
public static long getDirectorySizeCommonIO(File dir) {
return FileUtils.sizeOfDirectory(dir);
}
4. Legacy IO
In legacy IO, we can use file.listFiles()
to walk a directory recursively, and file.length()
to sum the size of all files.
public static long getDirectorySizeLegacy(File dir) {
long length = 0;
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile())
length += file.length();
else
length += getDirectorySizeLegacy(file);
}
}
return length;
}
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
Thanks it is work fine! 🙂