Get the free space of this partition in Java


The method java.io.File.getFreeSpace() is used to obtain the free space in the form of unallocated bytes for the partition specified by the required abstract path name. This method requires no parameters and it returns the unallocated bytes for the partition.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File[] roots = File.listRoots();
      try {
         for(File r : roots) {
         System.out.println(r);
         System.out.println("Free space = " + r.getFreeSpace());
      }
   } catch(Exception e) {
      e.printStackTrace();
   }
}
}

The output of the above program is as follows −

Output

C:\
Free space = 317686128640
D:\
Free space = 83022270464
E:\
Free space = 23645868032
F:\
Free space = 0

Note − The output may vary on Online Compilers.

Now let us understand the above program.

The method java.io.File.getFreeSpace() is used to obtain free space in the form of unallocated bytes. A code snippet that demonstrates this is given as follows −

File[] roots = File.listRoots();
try {
   for(File r : roots) {
      System.out.println(r);
      System.out.println("Free space = " + r.getFreeSpace());
   }
} catch(Exception e) {
   e.printStackTrace();
}

Updated on: 30-Jul-2019

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements