Files.lines()
Reads a file lazily as a stream of lines, without loading it into memory.
Available since: Java 8
Syntax
static Stream<String> lines(Path path) throws IOExceptionParameters
| Parameter | Type | Description |
|---|---|---|
| path | Path | The path to the file. |
Return value
Stream<String>A stream of lines that must be closed.
Examples
Counting error lines in a log; try-with-resources closes the file:
void main() throws IOException {
Path log = Path.of("app.log");
Files.writeString(log, "INFO start\nERROR disk\nINFO ok\nERROR net\n");
try (Stream<String> lines = Files.lines(log)) {
long errors = lines.filter(line -> line.startsWith("ERROR")).count();
IO.println(errors);
}
Files.delete(log);
}Output:
2Notes
The stream keeps the file open, so declare it in try (...). Without closing, the file may stay locked (especially on Windows), and Files.delete() fails.
See also
- Files.readAllLines() — Reads a text file into a list of lines.
- BufferedReader — Reads text line by line with buffering — the classic way to process large files.
- try / catch / finally — Catches exceptions; finally always runs, and try-with-resources closes resources for you.
Related recipes
In the tutorial
- Reading and writing files — Reading and writing text files in Java — Files.writeString, readString, readAllLines, write, appending to the end, Files.lines and buffered streams.