Pages Navigation Menu

Coding is much easier than you think

Calculate Free Disk Space in Java

Calculate Free Disk Space in Java

If you are a Java programmer, you may already have been asked this simple, stupid question: €œhow to find the free disk space left on my system?€.

It is possible to get the free disk space in Java 6 with a method in the class File, which returns the number of unallocated bytes in the partition named by the abstract path name. But you might be interested in the usable disk space (the one that is writable). It is even possible to get the total disk space of a partition with the method getTotalSpace().

Note : if you still use JDK 5, you’ll need to use an external library such as the Apache Commons and its FileSystem class


Example :


package com.SimpleCodeStuffs;
public class DiskSpace
    public static void main(String[] args)
    	File file = new File("C:");
        //total disk space in bytes.
    	long totalSpace = file.getTotalSpace(); 
        //unallocated free disk space in bytes.
    	long usableSpace = file.getUsableSpace(); 
    	//unallocated free disk space available to current user in bytes.
        long freeSpace = file.getFreeSpace(); 
    	System.out.println(" === Partition Detail ===");
    	System.out.println(" === bytes ===");
    	System.out.println("Total size : " + totalSpace + " bytes");
    	System.out.println("Space free : " + usableSpace + " bytes");
    	System.out.println("Space free : " + freeSpace + " bytes");
    	System.out.println(" === mega bytes ===");
    	System.out.println("Total size : " + totalSpace /1024 /1024 + " mb");
    	System.out.println("Space free : " + usableSpace /1024 /1024 + " mb");
    	System.out.println("Space free : " + freeSpace /1024 /1024 + " mb");


Output :

Display the disk space detail in c: partition.

=== Partition Detail ===
 === bytes ===
Total size : 52428795904 bytes
Space free : 33677811712 bytes
Space free : 33677811712 bytes
 === mega bytes ===
Total size : 49999 mb
Space free : 32117 mb
Space free : 32117 mb


Note : getFreeSpace() returns total free space available and getUsableSpace() returns amount of free space available to current user.

About Mohaideen Jamil

I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

%d bloggers like this: