How do I get free space of a drive or volume?

The getFreeSpaceKb(String path) method in the FileSystemUtils class can help you to calculate the free space of a drive or volume in kilobytes.

Beside using commons-io solution, you can use the File.getFreeSpace() method call provided in the Java 1.6 API. You can find an example of it in the following link: How do I get total space and free space of my disk?.

package org.kodejava.commons.io;

import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;

import java.io.IOException;

public class DiskFreeSpace {
    public static void main(String[] args) {
        try {
            String path = "F:/Temp";
            long freeSpaceKB = FileSystemUtils.freeSpaceKb(path);
            long freeSpaceMB = freeSpaceKB / FileUtils.ONE_KB;
            long freeSpaceGB = freeSpaceKB / FileUtils.ONE_MB;

            System.out.println("Size of " + path + " = " + freeSpaceKB + " KB");
            System.out.println("Size of " + path + " = " + freeSpaceMB + " MB");
            System.out.println("Size of " + path + " = " + freeSpaceGB + " GB");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

An example result of the code above is:

Size of F:/Temp = 323413052 KB
Size of F:/Temp = 315833 MB
Size of F:/Temp = 308 GB

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.