Home » Java programming language

How to check if directory exists in Java?

Checking directly exists or not: Here, we are going to learn how to check if directory exists in java?
Submitted by Preeti Jain, on July 03, 2019

  • We are using the File class that is an abstract representation of file and directory path. To check if a directory exists we have to follow a few steps:
  • Create a File object and at the time of instantiation, we have to give abstract path there for which we will be in searching.
  • By using exists() method of File. This method tests whether the directory exists. The return type of this method is boolean so it returns true if and only if the directory exists and otherwise it will return false.
  • We will understand clearly with the help of an example.

Example:

import java.io.File;

public class ToCheckDirectoryExists {
    public static void main(String[] args) {

        File dir_path1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles");
        File dir_path2 = new File("C:\\Users\\computer clinic\\Articles");

        // By using exists() method of File will check whether the 
        // specified directory exists or not and exist() method works 
        // with File class object because of its File method and 
        // it return Boolean return true if directory exists false otherwise.

        boolean dir_exists1 = dir_path1.exists();
        boolean dir_exists2 = dir_path2.exists();

        // By using getPath()method to retrieve the given path of the 
        // directory and dir_exists1 and dir_exists1 returns true 
        // when directory exists else false.
        System.out.println("Given Directory1 " + dir_path1.getPath() + " exists: " + dir_exists1);
        System.out.println("Given Directory2 " + dir_path2.getPath() + " is not exists: " + dir_exists2);
    }
}

Output

D:\Programs>javac ToCheckDirectoryExists.java

D:\Programs>java ToCheckDirectoryExists
Given Directory1 C:\Users\computer clinic\OneDrive\Articles exists: true
Given Directory2 C:\Users\computer clinic\Articles is not exists: false





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.