Question

IMO having both of these methods is redundant and really unclear! i can't quite understand why both of these methods are designed in Files API ??

Files.exist(..) returns true if file really exist and false if not exist or not having permission. so why in the hell there is a Files.notExist(..) ??

Oracle Docs says !Files.exists(…) is not equivalent to Files.notExists(…)!? maybe there is something that i couldn't understand well!!

what is benefit of using notExist() when there is an exist() method?

Était-ce utile?

La solution

I think the javadoc is pretty clear why notExists is not a logical complement of the exists method. Logical complement B = !A means that if A is true, B is false and vice versa. This is not the case here as both methods may return false at the same time.

"Where it is not possible to determine if a file exists or not then both methods return false."

Files.exists JavaDoc

Files.notExists JavaDoc

Autres conseils

You provided the answer already in the link.

    The file is verified to exist.
    The file is verified to not exist.
    The file's status is unknown. This result can occur when the program does not have access to the file.

If both exists and notExists return false, the existence of the file cannot be verified.

That means if exists() or notExists() return true you can be sure of the result, if the return false it can mean that the state could not be determined. So use the appropriate method if you want to check for existence or non existence.

Let's say that you want to access an existing file at some location. If you want to be sure that the access doesn't fail due to the file's non-existence, you call exists( path,... ) and proceed only if this returns true.

Let's say that you want to create a new file at some location. If you want to be sure that the create doesn't fail due to the file's existence, you call notExists( path,... ) and proceed only if this returns true.

Note that the negation of exists to handle the second case is not a guarantee in the same way notExists() delivers. And vice versa for ! notExists in the first scenario.

Files.exists(...) and Files.notExists(...) are not redundant but gives different information as can be seen in below code

 LinkOption linkOptions[] = new LinkOption[] { LinkOption.NOFOLLOW_LINKS };
    Path filePath = Paths.get("application.properties");
    if (Files.exists(filePath, linkOptions))
    {
      System.out.println("file exists!");
    } else if (Files.notExists(filePath, linkOptions))
    {
      System.out.println("file does not exist!");
    } else
    {
      System.out.println("file's status is unknown!");
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top