How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl\'s
-e $filename>
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.