Home » Java programming language

Java File Class long getFreeSpace() method with Example

Java File Class long getFreeSpace() method: Here, we are going to learn about the long getFreeSpace() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 11, 2019

File Class long getFreeSpace()

  • This method is available in package java.io.File.getFreeSpace().
  • This method is used to return the size of unallocated space(Space in terms of bytes) which is represented in the file pathname if the path exists and if the path does not exists then it return 0L(i.e. it return a long integer value that's why it is 0L).
  • The return type of this method is long so the size of unallocated bytes is of long type.
  • This method gives a rough idea that how much space remains or in other words how much space is free and the thing needs to remember that there is no guarantee of an exact number of unallocated bytes in the given pathname.
  • This method may raise an exception (i.e. Security Exception) if the function does not allow to be a file created.


    long getFreeSpace(){


We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is long i.e. it returns the size of unallocated bytes else it return 0L if path does not exists.

Java program to demonstrate example of getFreeSpace() method

// import the File class because we will use File class methods
import java.io.File;

// import the Exception class because it may raise an exception 
/// when working with files
import java.lang.Exception;

public class GetFreeSpace {
    public static void main(String[] args) {
        try {
            // Specify the path of file and we use double slashes to 
            // escape '\' character sequence for windows otherwise 
            // it will be considerable as url.
            File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
            File file2 = new File("C:\\java.txt");

            // By using getFreeSpace() return the size of free or 
            // unallocated space of the partition in the filepath 
            // because here filepath exists .
            System.out.println("The Free Space in File 1 :" + " " + file1.getFreeSpace());

            // By using getFreeSpace() return 0L because here filepath does not exists
            System.out.println("This Free Space in File 2 :" + " " + file2.getFreeSpace());

        } catch (Exception e) {
            System.out.println("An error occurred.");


D:\Programs>javac GetFreeSpace.java

D:\Programs>java GetFreeSpace
The Free Space in File 1 : 266079727616
This Free Space in File 2 : 0

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.