How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl\'s
-e $filename
Using java.io.File:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
You can use the following: File.exists()
f.isFile() && f.canRead()
first hit for "java file exists" on google:
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}
It's also well worth getting familiar with Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html This has additional methods for managing files and often better than JDK.