Java File getFreeSpace() method with examples

January 04, 2020 No comments Java IO Examples File getFreeSpace

1. Introduction

The getFreeSpace() method returns the number of unallocated bytes in the partition. The result is not guaranteed but should be treated as a hint. It is most likely that getFreeSpace() returns the accurate value immediately after this call.

2. Method signature

public long getFreeSpace()


  • method does not take any parameter


  • long - the number or unallocated bytes on the partition


  • SecurityException - if a security manager throw en error

3. Examples

3.1. The program that checks the free space of the main Linux partition under /dev/sbdb2



public class FrontBackend {

    public static void main(String args[]) {

        try {
            File main = new File("/dev/sdb2");

                    String.format("Free space of main partition : %d bytes (%d mb)", main.getFreeSpace(), main.getFreeSpace() / 1024 / 1024));

        } catch (Exception e) {

The output:

Free space of main partition : 8310472704 bytes (7925 mb)

4. Conclusion

In this short article, we presented the File.getFreeSpace() method with a simple example of how to use it in a real-life situation. This method gave the most accurate value a moment after the call, but in most cases, the result should be treated as a hint.

{{ message }}

{{ 'Comments are closed.' | trans }}