How to check if a file exists in Java

The File Object has an exists methods that returns true if a file exists.

Call the following method:


Here an example of checking if a file exists in Java. The code first creates a File Object with the file path; then it calls the method exists to that returns true if the file exists. Finally, depending in the value of the boolean returned, a message is written in the output.

1- Create the following java file:


public class FileExistsJava {

	public static void main(String[] argv){

		File file = new File( "V:/tmp/test.txt" );

		if ( file.exists() )
			System.out.println( "The file exists." );
			System.out.println( "The file doesn't exist." );

The output will be:

The file exists.


java io

Recent Comments