This simple Java program helps you to get the free disk space on your windows machines. Here I have used three methods for getting the disk space from your system.
- getTotalSpace()
- getUsableSpace()
- getFreeSpace()
The above methods are introduced from Java 6.0 and as part of the java.io package. The below example prints the disk space in bytes and mega bytes.
DiskSpaceExample.java
package javabeat.net.core; import java.io.File; import java.io.IOException; public class DiskSpaceExample { public static void main(String[] args) { File file = new File("d:"); long usableSpaceVar = file.getUsableSpace(); long totalSpaceVar = file.getTotalSpace(); long freeSpaceVar = file.getFreeSpace(); System.out.println(" ------- Disk Space Information in Bytes------"); System.out.println("Total disk size for d: " + totalSpaceVar + " bytes"); System.out.println("Space free on d: " + usableSpaceVar + " bytes"); System.out.println("Space free on d: " + freeSpaceVar + " bytes"); System.out.println(" ------- Disk Space Information in Mega Bytes (MB)------"); System.out.println("Total disk size for d: " + totalSpaceVar / 1024 / 1024 + " mega bytes"); System.out.println("Space free on d: " + usableSpaceVar / 1024 / 1024 + " mega bytes"); System.out.println("Space free on d: " + freeSpaceVar / 1024 / 1024 + " mega bytes"); } }
Output…
------- Disk Space Information in Bytes------ Total disk size for d: 4853467889 bytes Space free on d: 5853467889 bytes Space free on d: 5853467889 bytes ------- Disk Space Information in Mega Bytes (MB)------ Total disk size for d: 4628 mb Space free on d: 5582 mb Space free on d: 5582 mb