How do I check if a file exists?

To check if a file or a directory exists we can utilise method. This method return either true or false. Before we can wether it is 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 FileExist {
    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!

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply