Alternative to File.exists () in Java

I never thought this would happen to me, but I ran into the first error in Java:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5003595

I am pretty much in the same situation as described in the error (NFS on linux), and I see that File.exists () does not return the correct value (at least not right away).

So my question is: is there an alternative to this method of checking for a file? I would prefer it to be OS agnostic, if possible.

EDIT: I found a workaround. If you call "ls $ filedir", NFS updates all caches / metadata that cause Java problems, and File.exists () returns the correct value. Of course, this is not entirely ideal, since it harms portability, but there are ways to deal with this problem.

Thanks, Ben

+6
java file-io
source share
6 answers

The main problem you are working with in NFS is that it caches attribute, file, and directory data. This means that the information may be outdated. Perhaps you can turn off caching, you will see a significant decrease in performance.

It is important to remember that NFS is not a messaging service and is not intended for the timely delivery of data.

+5
source share

I had the same problem and solved it by calling file.getParentFile().list() . Essentially, this is the same as your solution, but OS is agnostic.

+6
source share

What happens if File.exists() returns true, then someone will delete the file / your NFS server will leave, and then you will try to open the file? Basically, File.exists() useless, since you need to handle exceptions that may occur when opening a file.

+5
source share

All File.exists tell you if a file exists at some point in the past. This does not tell you:

  • Will it exist when trying to open it.
  • You have permission to open it.
  • Anything useful at all really

Therefore, try to create an application so that it can process files that do not exist without trying to check it in advance. (When working with a file, you will have to handle various exceptions.)

+4
source share

I notice that the Java 7 method java.nio.file.Path.exists () returns false if the file does not exist or its existence cannot be determined. Thus, it seems that false negatives will exist for some time and that your code will have to tolerate them.

+2
source share

An obvious alternative is File.isFile (). Try it first.

Although reading read-only files will be inaccurate, you can always use File.canWrite () to check if the file exists.

If both of the above fail, you can use File.length (). If it returns 0L, you know that the file does not exist.

+1
source share

All Articles