Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why both Files.exists(…) and Files.notExists(…)?

Tags:

java

java-io

api

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?

like image 972
Morteza Adi Avatar asked Jan 24 '14 14:01

Morteza Adi


People also ask

How do you check a file exists or not in Java?

To test to see if a file or directory exists, use the exists method of the Java File class, as shown in this example: File tmpDir = new File("/var/tmp"); boolean exists = tmpDir. exists(); The existing method of the Java File class returns true if the file or directory exists, and false otherwise.

Which of the following returns true if the file at the specified path exists or false otherwise?

Files. exists(): Returns true if the file exists; false if the file does not exist or its existence cannot be determined.

What happens if a program attempts to open a file for reading but the file does not exist Java?

FileNotFoundException is a checked exception in Java that occurs when an attempt to open a file denoted by a specified pathname fails. This exception is thrown by the FileInputStream , FileOutputStream , and RandomAccessFile constructors when a file with the specified pathname either does not exist or is inaccessible.


2 Answers

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

like image 77
peter.petrov Avatar answered Sep 24 '22 11:09

peter.petrov


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.

like image 43
Leonard Brünings Avatar answered Sep 24 '22 11:09

Leonard Brünings