Java Programming Tutorials

Java programming tutorials with many code examples!

Java File – display space on disk


How to get and display disk space information in Java? In this post we’re going to show an example that does that using Java File from package.

Since Java 6 the class comes with three methods that provide information about disk space on partition specified by file:

  • public long getTotalSpace()
    Returns total number of bytes on the current partition.
  • public long getFreeSpace()
    Returns number of unallocated bytes on the current partition.
  • public long getUsableSpace()
    Returns number of bytes on the current partition available for this JVM.

To use the methods you need to create an instance of File object that will have some path name. This way JVM can get data for the partition on which the file is located. Let’s see that in action!


The code is very simple. We create a File object that point to the current directory, which means that we want space information the partition on which the current directory is located. Next we get the data and convert to human-friendly form – gigabytes (keep in mind that the numbers returned by the space methods are in bytes):



public class FileDiskUsageExample {

    private static final int GB = 1024 * 1024 * 1024;

    public static final void main(final String[] args) {
        File file = new File(".");
        System.out.printf("    Total: %d GB%n", file.getTotalSpace() / GB);
        System.out.printf("     Free: %d GB%n", file.getFreeSpace() / GB);
        System.out.printf("Available: %d GB%n", file.getUsableSpace() / GB);


Sample output of the program on my laptop:

    Total: 269 GB
     Free: 183 GB
Available: 169 GB

Note that not all the size reported as Free is Available for use by this Java Virtual Machine. That’s why the numbers are different.

Was it helpful? Share!