Java.io.File.getFreeSpace() Method

Advertisements


Description

The java.io.File.getFreeSpace() method returns the number of unallocated bytes in the partition named by this abstract path name. The returned number of unallocated bytes are not a gurantee. The count of unallocated bytes is likely to be accurate immediately after this call and inaccurate by any external I/O operations.

Declaration

Following is the declaration for java.io.File.getFreeSpace() method:

public long getFreeSpace()

Parameters

  • NA

Return Value

This method returns unallocated bytes on the partition.

Exception

  • SecurityException -- if a security manager exists and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) denies read access to the file name by this abstract pathname.

Example

The following example shows the usage of java.io.File.getFreeSpace() method.

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      long v;
      boolean bool = false;
      
      try{
         // create new file
         f = new File("C:\\test.txt");
         
         // get number of unallocated bytes
         v = f.getFreeSpace();
         
         // true if the file path exists
         bool = f.exists();
         
         // if file exists
         if(bool)
         {
            // prints
            System.out.print("number of unallocated bytes: "+v);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Let us compile and run the above program, this will produce the following result:

number of unallocated bytes: 87738191872



Advertisements
Advertisements