I'm currently using the apache-commons FileUtils.sizeOfDirectory(File file) method to get the size of a directory. What I actually need tough is the size of the directory on disk, the one displayed by the du utility under Unix, just to be clear.
Is it possible to get this information in Java?
du
finds this information by recursing through the entire directory tree and adding the sizes of all files it finds. (After rounding each file size up to an allocation unit I think, and how it finds out what the allocation unit is I don't know).
You will have to do likewise, or spawn an external du
process to do it for you.
You need to recursively search through the folder tree.
If you're using Java 7 it's nice and fast.
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
size += attrs.size();
return super.visitFile(file, attrs);
}
});
In Java 6 you need to use File.listFiles()
recursively and manually check each file size. Be aware though that this is very slow. So if you're looking at large number of files it might be worth finding a solution that spawns to an external command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With