Check whether the given file is an existing file in Java


The method java.io.File.isFile() is used to check whether the given file specified by the abstract path name is an existing file in Java. This method returns true if the file specified by the abstract path name is a file and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("Is file? " + file.isFile());
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

Is file? true

Now let us understand the above program.

The method java.io.File.isFile() checks whether the file is a file or not and the boolean value that is returned by the method is printed. A code snippet that demonstrates this is given as follows −

try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("Is file? " + file.isFile());
} catch(Exception e) {
   e.printStackTrace();
}

Updated on: 30-Jul-2019

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements