Checking if a file or directory exist

In this section, you will learn how to check a file or directory exist or not.

Checking if a file or directory exist

In this section, you will learn how to check a file or directory exist or not.

Checking if a file or directory exist

Checking if a file or directory exist

In this section you will learn how to check whether a file or a directory exist or not. The " java.io " package provide a method exist() which return true or false. This method will return "true" if file or directory exist otherwise it returns "false". In the following program we will create a object of file class and check whether file or directory exist or not.

import java.io.File;

public class DirectoryExist
{
	public static void main(String args[])
	{
		File file = new File("C://Documents and Settings//satya//Desktop//Temp");
		if(file.exists()){
		    System.out.println("File Exists");
		}else{
		
		    boolean check = file.mkdir();
		    if(check)System.out.println("Directory Created = "+file.getName());
		    else System.out.println("Sorry could not create directory");
		}
	}
}

Description : In the above code first we create an object of file class. Passing path as argument to the file class, will create a directory at the same position. The if condition checks for the file or directory existence in path by method exist(), that returns true if directory is already created and print "file Exist" to the console. If file is not there then exist() method will return false and control execute the else statement which create a directory by mkdir() method of file class and print the name of the directory to the console.

Output of the program :

Download SourceCode

If the Directory exist then the output will be as follows.