Java - Check if a file or directory exist

Posted on November 2, 2016

The File class provide a method, called exists(), for testing whether the file or directory exists. The exists() method return true if only if the file or directory exists; otherwise false.

See the below example.



 * @author imssbora
 * Nov 2, 2016
public class CheckFileDirectoryExample {
	public static void main(String[] args) {
		/*Check file if exist*/
		File file=new File("C:\\Program Files\\Java\\jdk1.8.0_71\\bin\\java.exe");
		System.out.println("File exist: "+file.exists());
		/*Check directory if exist*/
		File directory=new File("C:\\Program Files\\Java\\jdk1.8.0_71\\bin");
		System.out.println("Directory exist: "+directory.exists());


File exist: true
Directory exist: true