I'm unable to think of a realistic use case for the method java.io.File.exists()
or its equivalent in Java 7 java.nio.file.Files.exists(Path)
. It seems that isFile()
or isDirectory()
would be preferable in all cases (or canRead()
, canWrite()
, etc.).
For example, in How do I check if a file exists in Java?, the accepted answer seems silly, as the second answer points out.
Can anyone give an example where it's useful to know that a thing exists, without knowing whether the thing is a file or directory?
EDIT: I understand what File.exists()
does. My question is, when would that functionality ever help someone? I'm searching for an example like, "Use File.exists()
when _ _ _ _ _ _, because neither File.isFile()
nor File.isDirectory()
add any value in that case."
In retrospect, I think my confusion here was regarding two seemingly contradictory statements in the JavaDoc of the File
class. The first sentence defines the class as,
An abstract representation of file and directory pathnames.
That sounds like a clear dichotomy; but further in, the doc counters it with,
Instances of this class may or may not denote an actual file-system object such as a file or a directory.
I think an example of a third file-system object would have helped immensely in the documentation; but that category seems to lack even a name, resulting in the awkward phrasing of the JavaDoc for the Files
class: a collection of static methods,
that operate on files, directories, or other types of files.
In the accepted answer, @koral refers to these other types as "special files". That seems apt to me. They are so special, I didn't know they existed.
length
. – Trill