java.io.File getFreeSpace()

Description

On this document we will be showing a java example on how to use the getFreeSpace() method of File Class. This method returns the number of unallocated bytes in the partition named by this abstract path name.

The returned number of unallocated bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.

Throws:

  • SecurityException – If a security manager has been installed and it denies RuntimePermission(“getFileSystemAttributes”) or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathname

Method Syntax

public long getFreeSpace()

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns a long which denotes the number of unallocated bytes on the partition or 0L if the abstract pathname does not name a partition. This value will be less than or equal to the total file system size returned by getTotalSpace().

Compatibility

Requires Java 1.6 and up

Java File getFreeSpace() Example

Below is a java code demonstrates the use of getFreeSpace() method of File class. The example presented might be simple however it shows the behaviour of the getFreeSpace() method of File class. To make the print outs of the free space available we made some calculations to print out the equivalent in Kb, Mb and Gb.

package com.javatutorialhq.java.examples;

import java.io.File;

/*
 * This example source code demonstrates the use of  
 * getFreeSpace() method of File class.
 * 
 */

public class FileGetFreeSpaceExample {

	public static void main(String[] args) {

		// initialize File object
		File file = new File("C:");

		// get the free space available
		Long space = file.getFreeSpace();
		double spaceKb = space/1000;
		double spaceMb = space/1000000;
		double spaceGb = space/1000000000;
		
		System.out.println("Free Space in Kb:" + spaceKb +" Kb.");
		System.out.println("Free Space in Mb:" + spaceMb +" Mb.");
		System.out.println("Free Space in Gb:" + spaceGb +" Gb.");
	}
}

Sample Output

Below is the sample output when you run the above example.

java lang File getFreeSpace() example output