Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a file exists

Short answer

Suppose config.txt is next to the program. Files.exists() checks whether there is a file or folder at the path:

void main() {
    IO.println(Files.exists(Path.of("config.txt")));
    IO.println(Files.exists(Path.of("missing.txt")));
}

Output:

true
false

File or folder

isRegularFile() and isDirectory() tell you what exactly is at the path:

void main() {
    Path path = Path.of("config.txt");
 
    IO.println(Files.isRegularFile(path));
    IO.println(Files.isDirectory(path));
    IO.println(Files.isDirectory(Path.of(".")));
}

Output:

true
false
true

Access rights

isReadable() and isWritable() check whether you can read and write:

void main() {
    Path path = Path.of("config.txt");
    IO.println(Files.isReadable(path) + " " + Files.isWritable(path));
}

Output:

true true

Common mistake

Checking exists() and assuming the read will succeed. Another program can delete the file between the check and the read. The check is useful for user messages, but you still need to handle IOException:

void main() {
    Path path = Path.of("config.txt");
    try {
        IO.print(Files.readString(path));
    } catch (IOException e) {
        IO.println("Cannot read " + path + ": " + e.getMessage());
    }
}

Output:

debug=true

Functions used in this recipe

  • Files.exists() — Checks whether a file or folder exists. Related: isDirectory(), isRegularFile(), size().

Thanks for reading!

Donate to the site — we work hard for you.