Home Java Beginners Determining if a File or Directory exist



Determining if a File or Directory exist
Posted on: June 7, 2007 at 12:00 AM
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.

Code of this program is given below:

import java.io.*;

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);
  
  }else{
  // 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:

Related Tags for Determining if a File or Directory exist:
cfileclassobjectdirectoryiomethodproblemvirmirsareturnusingthissimplecreatecheckifconditionexistsprogramtorameilitnotlswiseimceinnormasmtrminminjclestruestsemdirmeobjprotorsurnrecttermctordirectatkisirhaicellivmplfolloweaandsasimwingwisxissthcondavstexictoetermetermjepleplprmindonogrolo


Ask Questions?    Discuss: Determining if a File or Directory exist   View All Comments

Post your Comment


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

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.