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.
Answering to the last question of @jaco0646:
Use File.exists()
when dealing with special files like named pipes, sockets or device files.
Those are not regular files nor directories nor symlinks so both File.isFile()
and File.isDirectory()
will return false
while File.exists()
will return true
. For example /dev/null
(on Unix compatible OSes) is a device file.
Theoretically there may be performance differences visible when processing large amounts of files. This depends also on filesystem, JVM implementation details, OS etc.
Eg. on Android File.exists()
is implemented using access()
system call while File.isFile()
/File.isDirectory()
use stat()
. In this case processing stat()
output requires more logic in userspace than access()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With