Thursday, March 8, 2012

How to get free disk space of a drive in java ?

JDK 1.6 provides few new methods  getTotalSpace(),getFreeSpace(), bundled with java.io.File. These methods provides essential information regarding disk space.

getFreeSpace() method-   Returns the number of unallocated bytes in the partition named by this abstract path name.
getTotalSpace() method - Returns the size of the partition named by this abstract pathname.


Here is the code: 

import java.io.File;

/**
 * Program that returns the number of unallocated bytes , total space in the partition.
 *
 * @author abdul
 *
 */
public class DiskDetail {
    public static void main(String[] args) {
        File file = new File("C:");
        long totalSpace = file.getTotalSpace(); // total disk space in bytes.
        long freeSpace = file.getFreeSpace(); // unallocated / free disk space
        long  diskUsage = (totalSpace - freeSpace);
       
        System.out.println("Total size : " + totalSpace + " bytes");
        System.out.println("Space free : " + freeSpace + " bytes");
        System.out.println("Used Space : " + diskUsage + "bytes");
    }
}

Output:
Total size : 107373129728 bytes
Space free : 44510306304 bytes
Used Space : 62862823424bytes

Reference: 

http://docs.oracle.com/javase/6/docs/api/java/io/File.html