Open In App

FileStore getUnallocatedSpace() method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The getUnallocatedSpace() method of a FileStore class is used to get the number of unallocated bytes in the file store. This method is useful to check free space. This method returns the available unallocated space as a long value.
Syntax: 

public abstract long getUnallocatedSpace()
                     throws IOException

Parameters: This method accepts nothing.
Return value: This method returns the available unallocated space as a long value.
Exception: This method throws IOException if an I/O error occurs.
Below programs illustrate the getUnallocatedSpace() method: 
Program 1: 

Java




// Java program to demonstrate
// FileStore.getUnallocatedSpace() method
 
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class GFG {
 
    public static void main(String[] args)
    {
        // create the object of Path
        Path path
            = Paths.get(
                "E:\\Tutorials\\file.txt");
 
        // get FileStore object
        try {
 
            FileStore fs
                = Files.getFileStore(path);
 
            // print FileStore name and Total unused size
            System.out.println("FileStore Name: "
                               + fs.name());
            long bytes = fs.getUnallocatedSpace();
            long sizeInGB = bytes / (1024 * 1024 * 1024);
            System.out.println("Free Space : "
                               + sizeInGB + "GB");
        }
        catch (IOException e) {
 
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


Output: 

Program 2: 

Java




// Java program to demonstrate
// FileStore.getUnallocatedSpace() method
 
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class GFG {
 
    public static void main(String[] args)
    {
        // create the object of Path
        Path path
            = Paths.get(
                "C:\\Movies\\001.txt");
 
        // get FileStore object
        try {
 
            FileStore fs
                = Files.getFileStore(path);
 
            // print FileStore name and Total size
            System.out.println("FileStore Name: "
                               + fs.name());
            System.out.println("Free Space in bytes: "
                               + fs.getUnallocatedSpace());
        }
        catch (IOException e) {
 
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


Output: 

References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/FileStore.html#getUnallocatedSpace()



Last Updated : 12 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads