Skip to content
Advertisement

JDK11 getFreeSpace and getTotalSpace from File is not matching df

I am seeing df -h giving output like below

root@vrni-platform:/var/lib# df -h
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/vg-var            110G   94G   11G  91% /var
root@vrni-platform:/var/lib# df -k
Filesystem                   1K-blocks     Used Available Use% Mounted on
/dev/mapper/vg-var           114756168 98318504  10585300  91% /var

But if I do the same from java like below

final File dataPath = new File("/var");
final long totalBytes = dataPath.getTotalSpace();
final long usedBytes = totalBytes - dataPath.getFreeSpace();
System.out.printf("Disk utilization: %.2f, Total bytes: %d, Used Bytes: %d", ((double)usedBytes/totalBytes * 100), totalBytes, usedBytes);```

It is printing like below

Disk utilization: 85.68, Total bytes: 117510316032, Used Bytes: 100678909952

Can someone let me know why is this discrepancy in disk utilization?

Environment

  • Ubuntu 18.04
  • Java – Zulu OpenJDK 11.0.11

Advertisement

Answer

As I also mentioned in the comments, the primary reason is that getFreeSpace seems to report something else than DFs ‘Avail’ or ‘Available’. Going by DFs ‘1K-blocks’ and ‘Used’, you also get a percentage of 85,68%, while going by ‘1K-blocks’ and ‘Available’ yields 91%. Also observe how DFs ‘Used’ and ‘Available’ (and ‘Used’ and ‘Avail’) do not add up to ‘1K-blocks’ (or ‘Size’)

As suggested by user16320675, using getUsableSpace might be a better method to use than getFreeSpace. As to the reasons for the difference between ‘1K-blocks’ – ‘Used’ and ‘Available’ in df, it might be better to ask that on https://unix.stackexchange.com/.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement