Alternative to File.exists() in Java

What happens if File.exists() returns true, then someone deletes the file/your NFS mount goes away, then you try and open the file? Basically, File.exists() is useless since you need to handle the exceptions that can arise from opening the file anyway.


All File.exists tells you is whether the file existed at some point in the past. It doesn't tell you:

  • Whether it will exist when you try to open it
  • Whether you have permission to open it
  • Anything useful at all, really

So try to design your application so it can handle files that don't exist without trying to check for that in advance. (You'll have to handle various exceptions when actually working with the file.)


The basic problem you have with NFS is that it caches attributes, files and directories information. This means the information can be out of date. You might be able to turn off caching, you will see a significant reduction in performance.

The important thing to remember is that NFS is not a messaging service and is not designed for timely delivery of data.


I experienced the same problem and solved it with a call to file.getParentFile().list(). Essentially the same as your solution, but OS agnostic.