Open In App

File getFreeSpace() method in Java with examples

Improve
Improve
Like Article
Like
Save
Share
Report

The getFreeSpace() function is a part of File class in Java. This function returns the unallocated size of the partition denoted by the abstract pathname, if the pathname does not exist then it returns 0L. This function gives a hint of the unallocated space of the partition but does not give any guarantee that the exact number of bytes are free. An error might be caused if an external application writes to the specified file, then the write operation might not succeed.

Function signature:

public long getFreeSpace()

Syntax:

long var = file.getFreeSpace();

Parameters: This method does not accept any parameter.

Return Value: The function returns long data type represents unallocated size of the partition in bytes

Exception: This method throws SecurityException if the method does not allow file to be created

Below programs illustrates the use of getFreeSpace() function:

Example 1: The file “F:\\program.txt” is a existing file in F: Directory .




// Java program to demonstrate
// getFreeSpace() method of File Class
  
import java.io.*;
  
public class solution {
    public static void main(String args[])
    {
  
        // Create an abstract pathname (File object)
        File f = new File("F:\\program.txt");
  
        // Display the free size of the partition
        // using the getFreeSpace() function
        System.out.println("Free Space: "
                           + f.getFreeSpace());
    }
}


Output:

Free Space: 174491860992

Example 2: The file “F:\\program1.txt” does not exist file in F: Directory .




// Java program to demonstrate
// getFreeSpace() method of File Class
  
import java.io.*;
  
public class solution {
    public static void main(String args[])
    {
  
        // Create an abstract pathname (File object)
        File f = new File("F:\\program1.txt");
  
        // Display the free size of the partition
        // using the getFreeSpace() function
        System.out.println("Free Space: "
                           + f.getFreeSpace());
    }
}


Output:

Free Space: 0

Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.



Last Updated : 29 Jul, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads