Monday, 11 April 2011

Calculate Free Disk Space in Java using Apache Commons IO

As a Java developer, lot of times I have to play around with file system. Sometimes I have to copy files/directories from one location to another; sometimes have to process certain files depending on certain pattern. In one of my test program, I wanted to calculate available disk space using Java. Lot of code snippets are available for this task. I liked the one using Apache Commons IO library.
Here is a simple trick for Java developers to calculate free diskspace. We have used Apache Commons IO library to calculate this.
Apache Commons IO library contains a class org.apache.commons.io.FileSystemUtils which can be used to calculate the free disk space in any system. Let us see the Java code for this.

 
import java.io.IOException;
 
import org.apache.commons.io.FileSystemUtils;
 
public class DiskSpace {
    public static void main(String[] args) {
        try {
 
            //calculate free disk space
            double freeDiskSpace = FileSystemUtils.freeSpaceKb("C:");
 
            //convert the number into gigabyte
            double freeDiskSpaceGB = freeDiskSpace / 1024 / 1024;
 
            System.out.println("Free Disk Space (GB):" + freeDiskSpaceGB);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output:
Free Disk Space (GB): 40.145268
In above code we used FileSystemUtils.freeSpaceKb( ) method to get the free space in kilo byte. This method invokes the command line to calculate the free disk space. You may want to call this method in following way to get free disk space in Windows and Linux.

FileSystemUtils.freeSpaceKb("C:");       // Windows
FileSystemUtils.freeSpaceKb("/volume");  // *nix
The free space is calculated via the command line. It uses ‘dir /-c’ on Windows, ‘df -kP’ on AIX/HP-UX and ‘df -k’ on other Unix.
In order to work, you must be running Windows, or have a implementation of Unix df that supports GNU format when passed -k (or -kP). If you are going to rely on this code, please check that it works on your OS by running some simple tests to compare the command line with the output from this class.

No comments:

Post a Comment