How can we check if file exists anywhere on the system in Java?


You can verify whether a particular file exists in the system in two ways using the File class and using the Files class.

Using The File class

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.

This class provides various methods to manipulate files, The exists a () method of it verifies whether the file or directory represented by the current File object exists if so, it returns true else it returns false.

Example

The following Java program verifies whether a specified file exists in the system. It uses the methods of the File class.

 Live Demo

import java.io.File;
public class FileExists {
   public static void main(String args[]) {
      //Creating a File object
      File file = new File("D:\source\sample.txt");
      //Verifying if the file exits
      boolean bool = file.exists();
      if(bool) {
         System.out.println("File exists");
      } else {
         System.out.println("File does not exist");
      }
   }
}

Output

File exists

The Files class

Since Java 7 the Files class was introduced this contains (static) methods that operate on files, directories, or other types of files.

The class to provides a method named exists(), which returns true if the file represented by the current object(s) exists in the system else it returns false.

Example

The following Java program verifies whether a specified file exists in the system. It uses the methods of the Files class.

 Live Demo

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileExists {
   public static void main(String args[]) {
      //Creating a Path object
      Path path = Paths.get("D:\sample.txt");
      //Verifying if the file exits
      boolean bool = Files.exists(path);
      if(bool) {
         System.out.println("File exists");
      } else {
         System.out.println("File does not exist");
      }
   }
}

Output

File does not exist

Updated on: 10-Sep-2019

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements