Java File : getTotalSpace(), getFreeSpace() and getUsableSpace()

By Arvind Rai, November 14, 2023
In Java 6, File class has some new methods.
getTotalSpace method gets total space in the specified directory by File instance.
getFreeSpace provides the available free space.
getUsableSpace provides the space available to virtual machine.

These methods returns long value
These methods are useful when we want to write some data on disk and need to know how much space are there to write data successfully. It is possible that just after getting disk space information from these methods, any other resource has written some data on disk. So these File method are not giving guarantee to write data successfully.

Example

package com.concretepage;
import java.io.File;

public class FileTest {

    public static void main(String... args){

        File file= new File("c:");

        //gets the total space in C drive in Byte

        long totalSpace=file.getTotalSpace();

        System.out.println("Total Space in Byte:"+totalSpace);

        //gets the free space in C drive in Byte

        long freeSpace=file.getFreeSpace();

        System.out.println("Free Space in Byte:"+freeSpace);

        //gets the usable space in c drive in Byte
        long usableSpace=file.getUsableSpace();
		
        System.out.println("Usable Space in Byte:"+usableSpace);
    }
}
Output
Total Space in Byte:63042482176
Free Space in Byte:6885539840
Usable Space in Byte:6885539840
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE







©2024 concretepage.com | Privacy Policy | Contact Us