How to check if a directory exists in java

Let’s learn how to check if a directory exists in java.

How to check if a directory exists in java

To check if directory exists or not java.io.File.exists() method is used.

File.exists() method returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.

Let’s see an example on how to check if directory exists or not.

import java.io.File;
public class CheckIfExists 
{
   public static void main(String[] args) 
   {
      try 
      {
         File fl = new File("B:/JavaExamples/CheckIfExists.txt");
         fl.createNewFile();
         System.out.println(fl.exists());
      }
      catch(Exception ex) 
      {
         ex.printStackTrace();
      }
   }
}


Output:

true


Also read – create file in java