How to check free disk space before creating a file

Suppose I need to create a file, and before that I need to check the free disk space for this operation.

Maybe he java.io.File.createNewFile()

will throw IOException

when there is not enough free space?

What's the best approach?

+3


source to share


3 answers


In java 1.6

  • public long getTotalSpace ()
  • public long getFreeSpace ()

Check this document

In java 1.7

  • getTotalSpace ()
  • getUnallocatedSpace ()
  • getUsableSpace ()

Check this document



In java 8

  • getFreeSpace ()
  • getUsableSpace ()

Check this document

Please check Example if you need help for the code

Edit: I found this interesting error while looking for your problem. Please take a look at this. PrintWriter does not throw IOException for full floppy disk

+4


source


You can use this to check the available space.

http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getFreeSpace%28%29



But an exception case is not a bad idea, in most cases I assume your free disk space will be ok

+2


source


in a simple way, you can check this.

   long freeSpace = new File("d:/").getFreeSpace(); //Here I am checking my d drive free space. 

      

-1


source







All Articles