Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read a whole file

Short answer

Suppose there is a file notes.txt next to the program:

Buy milk
Call Anna

Files.readString() reads it into one string. The method needs a path — a Path object:

void main() throws IOException {
    String text = Files.readString(Path.of("notes.txt"));
    IO.print(text);
}

Output:

Buy milk
Call Anna

The method can throw an IOException — a checked exception, which is why main has throws IOException.

A list of lines

readAllLines() splits the file into lines right away:

void main() throws IOException {
    List<String> lines = Files.readAllLines(Path.of("notes.txt"));
 
    IO.println(lines.size());
    IO.println(lines.getFirst());
}

Output:

2
Buy milk

Handling the error

If the file may be missing, catch the exception:

void main() {
    try {
        IO.println(Files.readString(Path.of("missing.txt")));
    } catch (NoSuchFileException e) {
        IO.println("File not found: " + e.getMessage());
    } catch (IOException e) {
        IO.println("Cannot read: " + e.getMessage());
    }
}

Output:

File not found: missing.txt

Encoding

Since Java 18 the default is UTF-8. If the file uses another encoding, specify it:

void main() throws IOException {
    String text = Files.readString(Path.of("notes.txt"), StandardCharsets.ISO_8859_1);
    IO.println(text.length());
}

Output:

19

Common mistake

Reading a huge file all at once. readString() and readAllLines() load everything into memory, and a multi-gigabyte file causes an OutOfMemoryError. Read large files line by line with Files.lines(). And remember that a relative path is resolved from the folder the program was started in, not from the source code folder.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.