How to read a whole file
Short answer
Suppose there is a file notes.txt next to the program:
Buy milk
Call AnnaFiles.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 AnnaThe 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 milkHandling 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.txtEncoding
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:
19Common 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
- Files.readString() — Reads a whole text file into one string.
- Files.readAllLines() — Reads a text file into a list of lines.
- Path.of() — Creates a Path object — a path to a file or folder.