Find free disk space using Java

Java Programming Java8Object Oriented Programming

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

Sr.No.Method & Description
1public long getFreeSpace()
Returns the number of unallocated bytes in the partition named by this abstract path name.
2public long getTotalSpace()
Returns the size of the partition named by this abstract pathname.
3public 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
raja
Published on 14-Aug-2018 10:35:13
Advertisements