How to get free disk space in Java

  • 05 April 2016
  • ADM

 

How to get free disk space in Java - images/logos/java.jpg

 

From Java 1.6 was introduced three methods to get details about the free/used space. These methods are bundled with java.io.File class.

  • getFreeSpace() - Returns the number of unallocated bytes in the partition named by this abstract path name.
  • getTotalSpace() - Returns the size of the partition named by this abstract pathname.
  • getUsableSpace() - Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.

These values are not a guarantee, because the same disk may be accessed from outside of the VM.

Example

package com.admfactory.io;

import java.io.File;

public class DiskFreeSpace {

    /**
     * Method to format bytes in human readable format
     * 
     * @param bytes
     *            - the value in bytes
     * @param digits
     *            - number of decimals to be displayed
     * @return human readable format string
     */
    public static String format(double bytes, int digits) {
        String[] dictionary = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
        int index = 0;
        for (index = 0; index < dictionary.length; index++) {
            if (bytes < 1024) {
                break;
            }
            bytes = bytes / 1024;
        }
        return String.format("%." + digits + "f", bytes) + " " + dictionary[index];
    }

    public static void main(String[] args) {
        String path = "c:\\";
        File c = new File(path);
        long freeSpace = c.getFreeSpace();
        long totalSpace = c.getTotalSpace();
        long usableSpace = c.getUsableSpace();

        System.out.println("'" + path + "' partition details");
        System.out.println();
        System.out.println("Free space: " + freeSpace + " bytes ==> " + format(freeSpace, 2));
        System.out.println("Total space: " + totalSpace + " bytes ==> " + format(totalSpace, 2));
        System.out.println("Usable space: " + usableSpace + " bytes ==> " + format(usableSpace, 2));
    }
}

Note: To display the bytes in human readable format I used the method copied from a previous post. Please visit How to convert byte size into human readable format in java for more details.

Output

'c:\' partition details

Free space: 208606650368 bytes ==> 194.28 GB
Total space: 500105736192 bytes ==> 465.76 GB
Usable space: 208606650368 bytes ==> 194.28 GB

Comparison

For Windows you can compare the free disk space: Right click on partition==>Properties.

How to get free disk space in Java - /images/DiskFreeSpace.png

You can notice a small difference for the free space between our java application and Properties window, but this is because the disk is used also by other applications and between I run the app and I open the Properties Windows it was several seconds.