Java - Check File Existence

Introduction

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.

Demo

import java.io.IOException;
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\\Main.java");

    boolean b = Files.exists(p);
    System.out.println(b);/*from ww w . j  av a2  s. c om*/
  }
}

Result