How To Get Free Disk Space In Java (Windows)

SHARE & COMMENT :

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.

  1. getTotalSpace()
  2. getUsableSpace()
  3. 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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better