How to get free, usable, and total disk space in Java


On this page, you will learn how to get free, usable, and total disk space in Java.  Java introduced getFreeSpace()getUsableSpace(), and getTotalSpace() in its 1.6 version to find the free space available in drive, usable space available in drive and total space of drive respectively.

Similar Post: Listing computer drives and its type using Java

The return type of all these methods is long, available in File class. These methods return the disk space size in bytes.

getFreeSpace()– Returns the number of unallocated bytes on the partition.

getUsableSpace()– Returns the number of available bytes on the partition.

getTotalSpace()– Return the total size of the partition in bytes.

Let’s see the complete example.

FindFreeSpaceOfDisk.java
package org.websparrow.file;

import java.io.File;

public class FindFreeSpaceOfDisk {

	public static void main(String[] args) {
		File[] computerDrives = File.listRoots();

		for (File drive : computerDrives) {
			System.out.println("Drive Name: " + drive);
			System.out.println("Free Space: " + drive.getFreeSpace());
			System.out.println("Usable Space: " + drive.getUsableSpace());
			System.out.println("Total Space: " + drive.getTotalSpace() + "\n");

		}
	}
}

Output:

Drive Name: C:\
Free Space: 103319486464
Usable Space: 103319486464
Total Space: 161061269504

Drive Name: D:\
Free Space: 21768769536
Usable Space: 21768769536
Total Space: 32749121536

Drive Name: E:\
Free Space: 55376027648
Usable Space: 55376027648
Total Space: 198814199808

Drive Name: F:\
Free Space: 46934781952
Usable Space: 46934781952
Total Space: 107374178304

Drive Name: G:\
Free Space: 0
Usable Space: 0
Total Space: 0

To calculate free, usable, and total disk space in Gigabytes (GB), divide all by (1024 * 1024 * 1024).

for (File drive : computerDrives) {
	
	System.out.println("Drive Name: " + drive);
	System.out.println("Free Space: " + drive.getFreeSpace() / (1024 * 1024 * 1024) + " GB");
	System.out.println("Usable Space: " + drive.getUsableSpace() / (1024 * 1024 * 1024) + " GB");
	System.out.println("Total Space: " + drive.getTotalSpace() / (1024 * 1024 * 1024) + " GB \n");
	
}

Output

Drive Name: C:\
Free Space: 96 GB
Usable Space: 96 GB
Total Space: 149 GB 

Drive Name: D:\
Free Space: 20 GB
Usable Space: 20 GB
Total Space: 30 GB 

Drive Name: E:\
Free Space: 51 GB
Usable Space: 51 GB
Total Space: 185 GB 

Drive Name: F:\
Free Space: 43 GB
Usable Space: 43 GB
Total Space: 99 GB 

Drive Name: G:\
Free Space: 0 GB
Usable Space: 0 GB
Total Space: 0 GB

Note: All the program tested in Windows environment.

References

  1. java.io.File

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.