JB Header
How to check for existence of a file in Java
This quick code tip shows how to check whether a file exists in Java. The Java code example used in the tutorial uses the NIO API's java.nio.file.Path and java.nio.file.Files classes to determine whether a file at the given path in the file system exists or not.

Java NIO-based code example to check for existence of a file
package com.javabrahman.corejava;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileExists {
  public static void main(String args[]){

    //Example of file which doesn't exist
    Path filePath_1= Paths.get("C:\\xyz.txt");
    boolean fileExists_1= Files.exists(filePath_1);
    System.out.println("File 'xyz.txt' exists: "+fileExists_1);

    //Example of file which exists
    Path filePath_2= Paths.get("C:\\JavaBrahman\\LEVEL1\\file1.txt");
    boolean fileExists_2= Files.exists(filePath_2);
    System.out.println("File ‘file1.txt’ exists: "+fileExists_2);
  }
}
 OUTPUT of the above code
File 'xyz.txt' exists: false
File 'file1.txt' exists: true
Explanation of the code
  • The above class FileExists checks for existence of 2 files - xyz.txt(which doesn't exist) and file1.txt(which exists) at their respective paths mentioned in the code.
  • The check for file existence is done in 2 steps(which need to be repeated for each file check). These steps are -
    1. Create an instance of Path using Paths.get() method with the complete file path passed as a String to it.
    2. Use Files.exist() method with the Path instance variable created in step 1 passed to it as parameter. Files.exist() returns a boolean value indicating the existence of the file - true if the file exists and false if it doesn't.
  • In the above example, the output is as expected - check for xyz.txt returns false as the file does not exist, while the returned value is true for file1.txt as it exists at the given file path.
How to check for existence of a file in Java - JavaBrahman