Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java directory size on disk?

Tags:

java

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?

like image 577
Husker14 Avatar asked Oct 29 '12 09:10

Husker14


2 Answers

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.

like image 84
hmakholm left over Monica Avatar answered Nov 05 '22 10:11

hmakholm left over Monica


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.

like image 2
Nano Avatar answered Nov 05 '22 10:11

Nano