Retrieve Free Disk Space with Java

Sometimes you wish to know how much disk space is left on your hard drive. There are several ways to do that. In this example I will show you how to do this with Apache commons.

You will need commons-io to run this example. You can get it either on the apache download page or use Maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>




Here is an example method returning the free drive space in KB of the drive on which your application is executed.

private long getFreeSpaceKb() {
    try {
        return FileSystemUtils.freeSpaceKb(new File(".").getAbsolutePath());
    } catch (IOException e) {
        return 0;
    }
}

You can change the code on line # 3 to retrieve the free space on specific drive:

FileSystemUtils.freeSpaceKb(new File("c:")); // in windows
FileSystemUtils.freeSpaceKb(new File("/")); // in Unix/Linux
0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments