Share on Google+Share on Google+

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 whether a file or a directory exist or not. The " " 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.


public class DirectoryExist
	public static void main(String args[])
		File file = new File("C://Documents and Settings//satya//Desktop//Temp");
		    System.out.println("File Exists");
		    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.



Posted on: June 20, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Checking if a file or directory exist  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image