17

I could not point out exact difference between getFreeSpace() and getUsableSpace() method of File class. When i run following code , got same o/p.

Class Start {
    public static void main(String [] args) {
        File myfile = new File("C:\\html\abc.txt");
        myfile.createNewFile();
        System.out.println("free space "+myfile.getFreeSpace()+"usable space "+myfile.getUsableSpace());
    }
}

O/P is

free space 445074731008 usable space 445074731008

Could any one tell me what is exact difference ?

yglodt
  • 13,807
  • 14
  • 91
  • 127
sar
  • 1,277
  • 3
  • 21
  • 48
  • On this link is suggested for real value to use getUsableSpace() : http://www.onkarjoshi.com/blog/203/difference-between-free-space-and-usable-space/ – ssasa Aug 27 '15 at 15:38

3 Answers3

16

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.

The java.io.File.getUsableSpace() method returns the number of bytes available to this virtual machine on the partitioned named by this abstract name. This method usually provide a more accurate estimate of how much new data can actually be written as this method checks for write permissions and other operating system restrictions.

Kick
  • 4,823
  • 3
  • 22
  • 29
2

The javadoc of getUsableSpace() says:

When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().


So we should choose getUsableSpace in most cases.


update:

notice below reported bug, in a very large disk the size of the space may exceed the limits of long type and return a negative value:

JDK-8179320 : File getUsableSpace() returns a negative number on very large file system

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
1

The difference is quite clearly stated in the Javadoc of the two methods:

getFreeSpace():

Returns the number of unallocated bytes in the partition named by this abstract path name. [...]

getUsableSpace():

Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace(). [...]

However, on most systems the two methods return the exact same number.

Itchy
  • 2,263
  • 28
  • 41