Home » Java programming language

Java File Class boolean exists() method with Example

Java File Class boolean exists() method: Here, we are going to learn about the boolean exists() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 10, 2019

File Class boolean exists()

  • This method is available in package java.io.File.exists().
  • This method is used to check whether files or directories exist or not in the given filepath.
  • The return type of this method is boolean i.e true or false If it returns true that means files or directories exist in the given path else returns false that means files does not exist in the given path.
  • This method may raise an exception(i.e. Security Exception) if the write access is not given to the file.

Syntax:

    boolean exists(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is boolean i.e. it returns true if file or directory exists in a given path else return false file not exists.

Java program to demonstrate example of exists() method

import java.io.File;

public class ToCheckDirectoryFileExists {
    public static void main(String[] args) {
        File path1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
        File path2 = new File("C:\\Users\\computer clinic\\Articles\\myjava1.txt");

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

        boolean file1_exists = path1.exists();
        boolean file2_exists = path2.exists();

        // By using getPath()method to retrieve the given 
        // path of the directory and file1_exists and file2_exists 
        // returns true when file exists else false.
        System.out.println("Given File1 " + path1.getPath() + " exists: " + file1_exists);
        System.out.println("Given File2 " + path2.getPath() + " is not exists: " + file2_exists);
    }
}

Output

D:\Programs>javac ToCheckDirectoryFileExists.java

D:\Programs>java ToCheckDirectoryFileExists
Given File1 C:\Users\computer clinic\OneDrive\Articles\myjava.txt exists: true
Given File2 C:\Users\computer clinic\Articles\myjava1.txt is not exists: false



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.