How to check a file exists in java

This example shows you how to check the file is exits or not in java.

You can check the file is exits or not by using file.exists() method, this method will returns true if file exists otherwise returns false.

Below is the example code of checking file exists or not in java.

package com.java.connect.io;

//How to check a file exists in java
import java.io.File;

public class FileExistExample {
	public static void main(String[] args) throws Exception {
		// Get the file object.
		File file = new File("lord_ganesh.jpg");

		// You can check the file is exits or not by using
		// file.exists() method, this method will returns true
		// if file exists otherwise returns false
		if (file.exists()) {
			System.out.println("File exist");
		} else {
			System.out.println("File does exist");
		}
	}
}

The output of the above example will be as in my system.

File exist