262. Using exists( ) method

exists( ) method is used to find out whether the file or folder exists at the path that is provided in File Class object creation statement as shown in the below example -

Example -

File file1 = new File("fileX.txt");
File folder1 = new File("ABZ");

if(file1.exists( ))
  System.out.println("A file with 'fileX.txt' name exists in your workspace");

if(folder1.exists( ))
  System.out.println("A folder with 'ABZ' name exists in your workspace");

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Class '' with main( ) method as shown below -

2. Lets go to our workspace location of our Program to find the existing file 'fileX.txt' and folder 'ABZ' as shown below -

3. Lets create a File Class objects for the above file and folder as shown below (Resolve any import errors) -

4. Check whether the file and Folder exists in our Project Workspace using exists( ) method and printing that they are available in our Project Workspace  when exists( ) method gives true as a results as shown below -

5. Save & Run the Java Class '' and observe that the statements will get printed as both the file and folder are available in our project workspace as shown below -

Hence exists( ) methods returns the boolean value true when the file or folder is available in the specified path of the File Class object creation statement. Else exists( ) will return false boolean value.

Please comment below to feedback or ask questions.

Methods of File Class will be explained in the next post.

No comments: