Home > Java > Desktop Applications > Build a Java Disk Space Calculator Command Line Application
One of the best ways to learn Java is by building small utilities that solve real problems. In this tutorial, we'll create a command line application that displays the amount of free and total disk space available on your computer.
This project introduces the File class and shows how Java can retrieve information about the file system without requiring any third-party libraries.
Our application will:
Create a new Java project with a single class called Main.
src └── Main.java
Copy the following code into Main.java.
import java.io.File; public class Main { public static void main(String[] args) { File[] drives = File.listRoots(); for (File drive : drives) { long total = drive.getTotalSpace(); long free = drive.getFreeSpace(); long used = total - free; long gb = 1024L * 1024L * 1024L; System.out.println("--------------------------------"); System.out.println("Drive : " + drive); System.out.println("Total : " + (total / gb) + " GB"); System.out.println("Used : " + (used / gb) + " GB"); System.out.println("Free : " + (free / gb) + " GB"); } } }
Open a command prompt and compile the application.
javac Main.java
Now run it.
java Main
-------------------------------- Drive : C:\ Total : 476 GB Used : 221 GB Free : 255 GB -------------------------------- Drive : D:\ Total : 931 GB Used : 418 GB Free : 513 GB
The File.listRoots() method returns every drive that Java can see on the computer.
For each drive we retrieve three important values.
Java returns these values in bytes, so we divide them by 1,024 × 1,024 × 1,024 to display them as gigabytes.
Once you have this working, try extending the application.
Although this is a small utility, it introduces an important part of the Java Standard Library. The File class provides information about files, folders and disk drives, making it useful for backup utilities, system monitoring tools and desktop applications.
Projects like this are far more representative of real Java development than inheritance examples involving animals or vehicles. They teach you how to solve practical problems while becoming familiar with the classes provided by the Java Standard Library.