Sub topic 9
Streaming Large Files with `Files.lines`
This chapter assumes you know Java classes, Stream, lambda expressions, and try-with-resources. It also assumes you can handle checked exceptions such as IOException.
When a text file is small, Files.readAllLines is convenient. It loads every line into a List<String>. That can use a large amount of memory for a large file. Files.lines returns a Stream<String> that reads lines lazily. Lazy means that a line is read when the stream needs it, rather than loading the entire file immediately.
How `Files.lines` works
The stream usually starts with a source, continues through intermediate operations such as filter or map, and finishes with a terminal operation such as count or forEach.
flowchart TD
A[Open the file] --> B[Files.lines returns a stream]
B --> C[Read a line when needed]
C --> D[Filter or transform the line]
D --> E[Terminal operation consumes the stream]
E --> F[Close the stream]The stream owns an open file. Always create it inside try-with-resources so the file is closed even when processing fails.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class CountLines {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
try (Stream<String> lines =
Files.lines(file, StandardCharsets.UTF_8)) {
long count = lines
.filter(line -> line.startsWith("s"))
.count();
System.out.println("Matching lines: " + count);
}
}
}The filter operation does not read the complete file first. The stream reads and tests lines as count requests them.
Choose the character encoding
A character encoding maps bytes in a file to characters in Java. UTF-8 is a common choice and supports many writing systems. Use the overload that accepts a Charset when the file format specifies an encoding:
Files.lines(file, StandardCharsets.UTF_8);The overload without a charset uses UTF-8. Writing the charset explicitly still makes the expected format clear to readers of your code.
Common errors
| Problem | Cause | Better practice |
|---|---|---|
| Memory use grows with file size | Using `readAllLines` for a large file | Use `Files.lines` |
| File remains open | The stream is not closed | Use try-with-resources |
| Unexpected characters | Wrong encoding | Specify the file's charset |
| Processing stops unexpectedly | A terminal operation was omitted | Add `count`, `forEach`, or another terminal operation |
A stream is single-use. After a terminal operation, do not try to use the same stream again. Open another stream if you need a second pass.
I/O can also fail during stream processing. Opening the stream reports IOException, while some later failures may appear as UncheckedIOException. Handle errors at the application boundary when appropriate.
Exercise
Why must a Files.lines stream be placed inside try-with-resources?
Show answer
The stream keeps the file open while it reads lines, so try-with-resources closes that file automatically.