3

Suppose I need to create a file and before that I need to check size of available disk space for that operation.

Maybe java.io.File.createNewFile() will throw a IOException when there is not enough free space?

What would be the best approach?

Vlad
  • 18,195
  • 4
  • 41
  • 71
Developer87
  • 2,448
  • 4
  • 23
  • 43
  • Note that checking disk space before an operation is no guarantee that there is enough diskspace whene the operation is done (and not enough space when checked doesn't guarantee that there is not enough space when the operation is done). On the other hand if the operation completes without out-of-space-error you're guaranteed that the disk space were enough. – skyking Jul 31 '15 at 08:29

3 Answers3

4

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 this Example if you need some help for code

Edit: I got this intresting bug while searching for your problem. Please have a look at this.PrintWriter does not throw IOException for full floppy disk

VedantK
  • 9,728
  • 7
  • 66
  • 71
2

You can use this to check available space.

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

But deal with excception is not a bad idea, in most case I assume that your free space on the disk will be ok

Community
  • 1
  • 1
khanou
  • 1,344
  • 11
  • 15
-1

in simple you can check like this.

   long freeSpace = new File("d:/").getFreeSpace(); //Here I am checking my d drive free space. 
Syam Danda
  • 587
  • 3
  • 12
  • 34