Check for file or directory in Java

Java 8Object Oriented ProgrammingProgramming

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.
raja
Published on 25-Feb-2019 16:40:42
Advertisements