Java Files.readAllLines and lines
Read all text lines into a list or process them lazily using a closable stream.
A simple example
Files.readAllLines and lines
- Start with Text with lines A and B
- Do this Read the lines
- Result Two entries
Syntax
public static List<String> readAllLines(Path path, Charset cs) throws IOException
JDK 21 declarations (4)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount confirmed riders in a shuttle manifest
A school shuttle manifest contains one status per line. A small run needs the first status for a receipt and a separate count of how many pupils have confirmed their seats.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path roster = Files.writeString(desk.resolve("bus.txt"), "yes\nwait\nyes\n");
System.out.println(Files.readAllLines(roster).getFirst());
try (var statuses = Files.lines(roster)) {
System.out.println(statuses.filter("yes"::equals).count());
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
yes 2
The trailing line break terminates the last record. It does not add another rider.
Read an empty classroom register
A teacher creates a new register before the first pupil arrives. The attendance count should be zero even though the file already exists and can be opened successfully.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path roster = Files.createFile(desk.resolve("empty.txt"));
System.out.println(Files.readAllLines(roster).isEmpty());
try (var lines = Files.lines(roster)) { System.out.println(lines.count()); }
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true 0
Neither API invents a blank record for a zero-byte file.
Read a studio sign-in sheet
A rehearsal has two names with a reserved blank row between them. Count every saved line, including an empty line between two entries. The end of input adds no extra line.
What to watch for
readAllLines stores the complete list in memory. A stream returned by lines must be closed even if processing stops early.