An existence check lets a program choose what to do before reading or writing.

exists check Files.exists asks the file system whether a path currently has an entry.
cleanup Deleting a temporary file after the example keeps later runs independent.

File Exists

create
FileExists.java
Replay: real traced execution (multi-file project)
import java.nio.file.Files;
import java.nio.file.Path;

public class FileExists {
    public static void main(String[] args) throws Exception {
        boolean create = true;
        Path path = Path.of("java21_exists.txt");
        Files.deleteIfExists(path);

        if (create) {
            Files.writeString(path, "ready");
        }

        boolean exists = Files.exists(path);
        Files.deleteIfExists(path);
        System.out.println("exists=" + exists);
    }
}
import java.nio.file.Files;
import java.nio.file.Path;

public class FileExists {
    public static void main(String[] args) throws Exception {
        boolean create = false;
        Path path = Path.of("java21_exists.txt");
        Files.deleteIfExists(path);

        if (create) {
            Files.writeString(path, "ready");
        }

        boolean exists = Files.exists(path);
        Files.deleteIfExists(path);
        System.out.println("exists=" + exists);
    }
}
  1. create ← true, path ← java21_exists.txt

    4public class FileExists {5    public static void main(String[] args) throws Exception {6        boolean create→ true = true;  //@create=false, true7        Path path→ java21_exists.txt = Path.of("java21_exists.txt");8        Files.deleteIfExists(pathjava21_exists.txt);
  2. if (create)

    10if (createtrue) {11    Files.writeString(pathjava21_exists.txt, "ready");12}
  3. exists ← true

    14    boolean exists→ true = Files.exists(pathjava21_exists.txt);15    Files.deleteIfExists(pathjava21_exists.txt);16    System.out.println("exists=" + existstrue);17}
    outputexists=true
  1. create ← false, path ← java21_exists.txt, exists ← false

    4public class FileExists {5    public static void main(String[] args) throws Exception {6        boolean create→ false = false;7        Path path→ java21_exists.txt = Path.of("java21_exists.txt");8        Files.deleteIfExists(pathjava21_exists.txt);910        if (create) {11            Files.writeString(path, "ready");12        }1314        boolean exists→ false = Files.exists(pathjava21_exists.txt);15        Files.deleteIfExists(pathjava21_exists.txt);16        System.out.println("exists=" + existsfalse);17    }
    outputexists=false