Home » Tip Bank » Java
  • Comment on this Article
Apr 29, 2021

How to List Drives in a System with Java

Here, we learn how to use Java’s sophisticated APIs to work with a file system. We will use Java’s java.io package and its File class to list any available drives on the computer and their total - and free - capacity at run time.

Believe is some sample code using the Java programming language to achieve this task:

*/

import java.io.*;

public class ListDrives
{
	
	public static void main(String args[])
	{
		ListDrives listDrives = new ListDrives();
		listDrives.proceed();
	}

	private void proceed()
	{

		File[] rootDrives = File.listRoots();
		if (rootDrives != null && rootDrives.length > 0) 
		{
			for (File fileAsDrive : rootDrives) {
				System.out.println("Drive: " + fileAsDrive);
				System.out.println("Total space: " + fileAsDrive.getTotalSpace() / (1024*1024*1024) + " GB");
				System.out.println("Free space: " + fileAsDrive.getFreeSpace() / (1024*1024*1024) + " GB");
			}
		}
		
	}
}

/*

This example Java program showing how to list the drives in a file system will give you the following output when run:

C:\MyPgms>java ListDrives
Drive: C:\
Total space: 101 GB
Free space: 55 GB
Drive: D:\
Total space: 273 GB
Free space: 263 GB
Drive: E:\
Total space: 100 GB
Free space: 99 GB
MS Sridhar
 
Submit a Tip
Submit a Tip Browse "Java" Tips
Browse "Java" Tips Browse All Tips
Browse All Tips
html-color-codes.info
htmlgoodies.com