Java - Check File Existence


Files class exists(Path p, LinkOption... options) and notExists(Path p, LinkOption... options) checks for the existence and non-existence of a file, respectively.

If it is not possible to determine whether a file exists, both methods return false.

To take an action when a file exists, use the exists() method.

To take an action when a file does not exist, use the notExists() method.


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

public class Main {
  public static void main(String[] args) throws IOException {
    // Create a Path object on Windows
    Path p = Paths.get("C:\\myData\\");

    boolean b = Files.exists(p);
    System.out.println(b);//  w  ww  .j a  v a 2  s  . c om