2

I am using java.io.File.length() method to get size of a file.

But for a sparse file this value can be very different from actual disk space used by that file.

Is there a way to get actual disk usage for the file?

The apparent size of a file is the number of bytes in a file. For example, a file containing the word ‘zoo’ with no newline would, of course, have an apparent size of 3. However, a sparse file created with this command:

dd bs=1 seek=2GiB if=/dev/null of=big

has an apparent size of 2 GiB, yet on most modern systems, it actually uses almost no disk space.

learner
  • 1,952
  • 7
  • 33
  • 62
  • 1
    This is highly OS dependent, so I would be quite surprised if there was a way in Java (I mean the standard JDK libraries) to do this. Anyway, there could be an obscure third-party library for that. – Jozef Chocholacek Aug 13 '15 at 11:22

1 Answers1

2

Use jnr-posix. Example usage:

import jnr.posix.*;

final POSIX p = POSIXFactory.getPOSIX();
final int S_BLKSIZE = 512; // from sys/stat.h
final FileStat stat = p.stat("/some/file.txt");
final long bytes = stat.blocks() * S_BLKSIZE;
Ben Alex
  • 1,519
  • 13
  • 9
  • not work on linux for stat.st_blocks is not implemented in jnr-posix at jnr.posix.util.DefaultPOSIXHandler.unimplementedError(DefaultPOSIXHandler.java:28) – yaoweijq Apr 16 '19 at 01:17