Check for file or directory in Java


The method java.io.File.isFile() is used to check whether the given file is an existing file in Java. Similarly, the method java.io.File.isDirectory() is used to check whether the given file is a directory in Java. Both of these methods require no parameters.

A program that demonstrates this is given as follows −

Example

public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         boolean fileFlag = file.isFile();
         if (fileFlag) {
            System.out.println("This is a file.");
         } else {
            System.out.println("This is not a file.");
         }
         boolean directoryFlag = file.isDirectory();
         if (directoryFlag) {
            System.out.println("This is a directory.");
         } else {
            System.out.println("This is not a directory.");
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

This is a file.
This is not a directory.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements