Find Free Disk Space Using Java



java.io.File class provides following useful methods to figure out the free disk space available.

Sr.No. Method & Description
1 public long getFreeSpace()
Returns the number of unallocated bytes in the partition named by this abstract path name.
2 public long getTotalSpace()
Returns the size of the partition named by this abstract pathname.
3 public long getUsableSpace()
Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.

Following example showcases the use of above methods.

Example Final

import java.io.File;
import java.text.NumberFormat;

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

      NumberFormat numberFormat = NumberFormat.getInstance();
      numberFormat.setMaximumFractionDigits(2);
      File cDrive = new File("C:\");

      double freeSpace = cDrive.getFreeSpace();
      double usableSpace = cDrive.getUsableSpace();
      double totalSpace = cDrive.getTotalSpace();
      double oneGB = 1024 * 1024 * 1024;

      System.out.println("Free Space: " +
      numberFormat.format(freeSpace/oneGB) + " GB");
      System.out.println("Usable Space: " +
      numberFormat.format(usableSpace/oneGB) + " GB");
      System.out.println("Total Space: " +
      numberFormat.format(totalSpace/oneGB) + " GB");
   }
}

Output

Free Space: 11.66 GB
Usable Space: 11.66 GB
Total Space: 97.56 GB
Updated on: 2020-06-21T14:37:34+05:30

904 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements