# Determine if file or directory exists in Java

Java 8Object Oriented ProgrammingProgramming

The method java.io.File.exists() is used to check whether a file or a directory exists or not. This method returns true if the file or directory specified by the abstract path name exists and false if it does not exist.

A program that demonstrates this is given as follows −

## Example

import java.io.File;
public class Demo {
public static void main(String[] args) {
try {
File file = new File("c:/JavaProgram/demo1.txt");
file.createNewFile();
System.out.println(file.exists());
} catch(Exception e) {
e.printStackTrace();
}
}
}

The output of the above program is as follows −

## Output

true

Now let us understand the above program.

The method java.io.File.exists() is used to check whether the file or directory exists or not and the boolean value that is returned by the method is printed. A code snippet that demonstrates this is given as follows −

try {
File file = new File("c:/JavaProgram/demo1.txt");
file.createNewFile();
System.out.println(file.exists());
} catch(Exception e) {
e.printStackTrace();
}
Published on 25-Feb-2019 12:15:17