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.


  • 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

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().


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.

Sample Output

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

java lang File getFreeSpace() example output

Suggested Reading List