Thursday, 23 August 2012

Calculating Disk Space in Java


In Java by using a few API's are there through which we can directly obtain the space given in a drive.



package com.test;

import java.io.File;

public class SizeInfo
{
    public static void main(String[] args)
    {

       System.out.print("Enter the drive: ");
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String path= null;
       try {
         path= br.readLine();

      File file = new File(path + ":");

//the size returned will be in bytes.

     long totalSpace = file.getTotalSpace();
     long usableSpace = file.getUsableSpace();
     long freeSpace = file.getFreeSpace();



     System.out.println("Total size : " + TotalSpace /1048576 + " Gb");
     System.out.println("Space free : " + UsableSpace /1048576 + " Gb");
     System.out.println("Space free : " + FreeSpace /1073741824 + " Gb");
}catch(Exception ex)
{
ex.printstacktrace();
}
    }
}


getUsableSpace() method does a few additional checks, about write permissions and actual space available to the user. Also, on some systems a certain percentage of total disk space is reserved for admin/root users. This can make your checks for space pass incorrectly if you happen to use the getFreeSpace() method.