How do I check if a file exists in Java?
To verify a file's existence in Java quickly, use Files.exists
from java.nio.file
:
The Boolean fileExists
will be true
if the file exists, and false
otherwise. This is a succinct and efficient method highly recommended for Java SE 7 and later versions.
Avoid false positives with directories
Confirming the existence of only a file (not a directory) requires a combination of exists()
and !isDirectory()
:
This ensures our existence check is for a file only – avoiding any confusion with directories.
File creation if non-existent
Creating a file only if it doesn't currently exist can be achieved with exists()
and createNewFile()
:
This snippet is useful when your logic involves creating a new file from scratch or working on a brand new set of data.
Taking full advantage of Java NIO.2
Introduced in Java 7, NIO.2's Files
class offers a clear API:
- Regular files:
Files.isRegularFile(path)
ensures the path is a file, not a directory or anything else. - Directories:
Files.isDirectory(path)
checks if a path points to a directory. - Uncertainty Principle: Both
Files.exists
andFiles.notExists
can returnfalse
when determining a file's existence isn't possible.
A simultaneous check for the file's existence and its readability would look like this:
Here, the code ensures the existence and accessibility of a file before performing any actions with it.
The Java 8 way
Java 8 introduced the Files
and Paths
classes, offering a preferred way to deal with files:
In the last example, the code avoids following symbolic links. This is useful when dealing with complex file system structures.
Ensure accuracy of file paths
Ensure that filePathString
is a valid path. Invalid paths lead to unexpected behaviour or errors. So, handle cases where the path may be invalid:
Was this article helpful?