- List all system drives in java.
- We will find out the free (available) , used and total space of each drive.
- We will list system drives using File.listRoots api.
- Find out the free (available), used and total space of each drive using following methods.
S.No. |
API |
Description |
1 |
getTotalSpace |
Returns the size of the partition named by this abstract pathname. |
2 |
getFreeSpace |
Returns the number of unallocated bytes in the partition named by this abstract path name. |
3 |
getUsableSpace |
Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. |
- We will format the disk space in GB.
- Similarly, we can format disk space in KB or MB.
Program: List system drive & their total, free, used space in java
package org.learn.io;
import java.io.File;
public class ListDrivesAndSpace {
public static void main(String[] args) {
double GB = 1024D * 1024D * 1024D;
//Format drive space as per your need
//double MB = 1024D * 1024D;
//double KB = 1024D;
File[] listDrives = File.listRoots();
System.out.println("Listing System drives:");
for(File drive: listDrives) {
System.out.printf("Drive: %s\n",drive);
System.out.printf("Total Space: %f GB\n",drive.getTotalSpace()/GB);
System.out.printf("Free Space: %f GB\n",drive.getFreeSpace()/GB);
System.out.printf("Usable Space: %f GB\n\n",drive.getUsableSpace()/GB);
}
}
}
Output: List system drive & their total, free, used space in java
Listing System drives:
Drive: C:\
Total Space: 234.728512 GB
Free Space: 186.074795 GB
Usable Space: 186.074795 GB
Drive: D:\
Total Space: 120.236324 GB
Free Space: 104.201542 GB
Usable Space: 104.201542 GB
Drive: E:\
Total Space: 120.971676 GB
Free Space: 67.195110 GB
Usable Space: 67.195110 GB