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

File Exists

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

public class FileExists {
    public static void main(String[] args) throws Exception {
        boolean create = ;
        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 = ;
        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);
    }
}
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.