How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl\'s
-e $filename
Don't use File constructor with String.
This may not work!
Instead of this use URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
For me a combination of the accepted answer by Sean A.O. Harney and the resulting comment by Cort3z seems to be the best solution.
Used the following snippet:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
Hope this could help someone.
By using nio in Java SE 7,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
If both exists
and notExists
return false, the existence of the file cannot be verified. (maybe no access right to this path)
You can check if path
is a directory or regular file.
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
Please check this Java SE 7 tutorial.
There are multiple ways to achieve this.
In case of just for existence. It could be file or a directory.
new File("/path/to/file").exists();
Check for file
File f = new File("/path/to/file");
if(f.exists() && f.isFile()) {}
Check for Directory.
File f = new File("/path/to/file");
if(f.exists() && f.isDirectory()) {}
Java 7 way.
Path path = Paths.get("/path/to/file");
Files.exists(path) // Existence
Files.isDirectory(path) // is Directory
Files.isRegularFile(path) // Regular file
Files.isSymbolicLink(path) // Symbolic Link
Don't. Just catch the FileNotFoundException.
The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:
Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.
I would recommend using isFile()
instead of exists()
. Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists()
will return true if your path points to a directory.
new File("path/to/file.txt").isFile();
new File("C:/").exists()
will return true but will not allow you to open and read from it as a file.