5

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?

Husker14
  • 586
  • 1
  • 5
  • 7

2 Answers2

8

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.

hmakholm left over Monica
  • 23,074
  • 3
  • 51
  • 73
  • I don't want to spawn du because I need the code to be platform independent. I'll try to look into allocation unit management. Thanks – Husker14 Oct 29 '12 at 11:58
2

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.

Nano
  • 51
  • 2
  • 1
    I don't need the size of the file (which is the one returned by the size() method), but the space occupied by the file on disk (a 10 byte file might occupy 32 bytes, for example). – Husker14 Oct 29 '12 at 12:00
  • Ah I see. Sorry. Misunderstood you there. – Nano Oct 29 '12 at 12:09
  • 1
    this might help then: http://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information – Nano Oct 29 '12 at 12:13