How do I check if a file exists?

To check if a file, or a directory exists we can utilize java.io.File.exists() 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.

package org.kodejava.io;

import java.io.File;
import java.io.FileNotFoundException;

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!";
            System.out.println(message);
            throw new FileNotFoundException(message);
        }

        // Continue with application logic here!
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.