Share on Google+Share on Google+

Determining if a File or Directory exist

In this section, you will learn how to determine a file or directory exit or not.

Determining if a File or Directory Exist


This is a very simple problem. You just have to determine whether a file or directory exists or not. If it exists it returns true otherwise in the else condition, it retunes vice-versa.

The following program creates an object of File class and checks whether the given file exists or not by using exists() method of the class.

We have used following methods:

exists(): It checks whether the file or directory denoted by this pathname exists or not.

Here is the video tutorial of "How to check if a folder exists in Java?":

Code of this program is given below:


public class FileOrDirectoryExists{
  public static void main(String args[]){
  File file=new File("Any file name or 
   directory whether exists or not"
  boolean exists = file.exists();
  if (!exists) {
  // It returns false if File or directory does not exist
  System.out.println("the file or directory 
  you are searching does not exist : " 
+ exists);
  // It returns true if File or directory exists
  System.out.println("the file or 
  directory you are searching does exist : " 
+ exists);

The output of the program is given below:

C:\java>java FileOrDirectoryExists
the file or directory you are searching does not exist : false

Download this example:


Posted on: June 7, 2007 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: Determining if a File or Directory exist   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
June 10, 2011
misleading comments

does not exist : false should be does not exist : true since it doesn't exist
June 13, 2013

It's a reielf to find someone who can explain things so well
September 7, 2011
method not found

I am trying to use this example about checking if a file exists. It seems like my compiler is not finding the method 'exists()' since it is asking me to create a class with the same name. Thank you.
March 4, 2012
Thanks for your post: true

if (!exists) { System.out.println("the file or directory you are searching does exist : " + exists); does exists? FALSE mens not exists } else { System.out.println("the file or directory you are searching does exist : " + exists); does exists? TRUE mens exists it's about logic, as i know when you code on java you need to write it like a book :D but thanks for your post Helped me a lot. i'm now on Java courses!
crystal x
May 18, 2012
gui implementation

could you give me example how to implementationon Java GUI?