How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl\'s
-e $filename
You can make it this way
import java.nio.file.Paths;
String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
//...do somethinh
}
File f = new File(filePathString);
This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:
f.createNewFile();
So f.exists()
can be used to check whether such a file exists or not.
I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.
The following snippet
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
is perfectly satifactory, because method isRegularFile
returns false
if file does not exist. Therefore, no need to check if Files.exists(...)
.
Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.
From Java Oracle documentation
Simple example with good coding practices and covering all cases :
private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
if (f.exists()) {
throw new FileAlreadyExistsException(f.getAbsolutePath());
} else {
try {
URL u = new URL(url);
FileUtils.copyURLToFile(u, f);
} catch (MalformedURLException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Reference and more examples at
https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations
There is specific purpose to design these methods. We can't say use anyone to check file exist or not.
Using Java 8:
if(Files.exists(Paths.get(filePathString))) {
// do something
}