How do I check if a file exists?

To check if a file or a directory exists we can utilize method. This method return either true or false. Before we can check whether its exists or not we need to create an instance of File that represent an abstract path name of the file or directory. After we have the File instance we can call the exists() method to validate it.



public class FileExists {
    public static void main(String[] args) throws Exception {
        // Create an abstract definition of configuration file to be
        // read.
        File file = new File("applicationContext-hibernate.xml");

        // Print the exact location of the file in file system.
        System.out.println("File = " + file.getAbsolutePath());

        // If configuration file, applicationContext-hibernate.xml
        // does not exist in the current path throws an exception.
        if (!file.exists()) {
            String message = "Cannot find configuration file!";
            throw new FileNotFoundException(message);

        // Continue with application logic here!