Calculate Free Disk Space In Java Using Apache Commons IO

Calculate Free Disk Space In Java Using Apache Commons IO

Friday, July 18, 2014

5:31 PM

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.

package net.viralpatel.java;

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.

 

Created with Microsoft OneNote 2013.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s