Sub topic 9
Streaming large files with Files.lines
This chapter assumes you can read small files with Files.readString and Files.readAllLines, that you know try-with-resources, and that you can use Stream operations such as filter, map and count. You need Java 11 or later.
Why whole-file reads stop working
Files.readAllLines returns a List<String> that holds every line in memory at once. A 4 GB log file can need well over 4 GB of heap, because each Java String carries object overhead. Many programs only need one pass over the data: count matches, sum a column, or copy selected lines elsewhere. They never need the whole file in memory.
Files.lines(Path) solves this. It returns a Stream<String> that reads lines on demand. Memory use depends on what you do with the lines, not on the file size.
How Files.lines works
Files.lines opens the file right away and returns a stream. It reads no content until you call a terminal operation such as count, forEach or collect. Each line is read only when the pipeline asks for it.
Two facts follow from this design:
- The stream holds an open file handle, so you must close it.
- Lines pass through the whole pipeline one at a time. A
filterfollowed bycountnever stores the lines.
Always close the stream
Stream implements AutoCloseable. Put the stream in a try-with-resources header so the file is released even when an exception occurs.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class CountErrors {
public static void main(String[] args) throws IOException {
Path log = Path.of("server.log");
Files.writeString(log, "INFO start\nERROR disk full\nINFO retry\nERROR timeout\n");
try (Stream<String> lines = Files.lines(log)) {
long errors = lines
.filter(line -> line.startsWith("ERROR"))
.count();
System.out.println("Errors: " + errors);
}
}
}This prints Errors: 2. The program writes its own input file first, so it runs as shown.
Choosing the charset
Files.lines(path) decodes the file as UTF-8. Use the two-argument form when the file uses another encoding:
Stream<String> lines = Files.lines(path, StandardCharsets.ISO_8859_1);Naming the charset, even when it is UTF-8, shows readers what the file contains. For the full discussion, see the chapter on character encodings.
Errors happen late and are unchecked
Files.lines throws a checked IOException when it cannot open the file, for example NoSuchFileException. That happens at the call, before any line is read.
Read errors occur later, while the terminal operation runs. A lambda or a stream pipeline cannot throw a checked exception, so the stream wraps these failures in UncheckedIOException. The original exception is available through getCause().
The most common case is a file whose bytes are not valid in the charset you chose. The next program writes a single byte, 0xE9 (the letter é in ISO-8859-1), which is not valid UTF-8. Then it reads the file as UTF-8.
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class BadEncoding {
public static void main(String[] args) throws IOException {
Path file = Path.of("latin1.txt");
Files.write(file, new byte[] {(byte) 0xE9, '\n'});
try (Stream<String> lines = Files.lines(file)) {
System.out.println(lines.count());
} catch (UncheckedIOException e) {
System.out.println("Read failed: " + e.getCause());
}
}
}The catch block prints a MalformedInputException. Note that you need both kinds of handler. The throws IOException clause on main covers the open step, and the catch for UncheckedIOException covers failures during the read. If you want one handler for both, catch IOException | UncheckedIOException.
Processing a file while keeping memory flat
A typical task is to parse a CSV file. This example skips the header and totals the second column:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class SumColumn {
public static void main(String[] args) throws IOException {
Path csv = Path.of("sales.csv");
Files.writeString(csv, "item,amount\napple,10\npear,25\nplum,7\n");
try (Stream<String> lines = Files.lines(csv)) {
int total = lines
.skip(1)
.map(line -> line.split(","))
.mapToInt(parts -> Integer.parseInt(parts[1].trim()))
.sum();
System.out.println("Total: " + total);
}
}
}This prints Total: 42. At any moment the program holds one line and its split array, whatever the file size.
A bad row throws NumberFormatException from inside the lambda. The try-with-resources block still closes the file, and the exception then propagates out.
What breaks the memory advantage
The stream is lazy, but some operations are not. Watch for these:
| Operation | Effect on memory |
|---|---|
| `filter`, `map`, `skip`, `limit`, `peek` | Process one line at a time. Memory stays flat. |
| `count`, `sum`, `anyMatch`, `findFirst` | Keep a small accumulator. `anyMatch` and `findFirst` stop reading early. |
| `forEach` | Flat, as long as the action does not store the lines. |
| `sorted` | Buffers every element before emitting any. |
| `distinct` | Remembers every distinct element seen. |
| `collect(toList())`, `toList()` | Holds every element that reaches it. |
| `Collectors.groupingBy` | Holds the groups, which can be as large as the input. |
Filtering before you collect keeps the result small. Counting words in a 10 GB file is fine if the number of distinct words is modest. The same program can run out of memory if almost every line is unique.
Do not let the stream escape
A method that returns the stream from inside try-with-resources hands the caller a closed stream. Calling any terminal operation on it throws IllegalStateException.
// Broken: the stream is closed when the method returns.
static Stream<String> firstLines(Path p) throws IOException {
try (Stream<String> lines = Files.lines(p)) {
return lines.limit(10);
}
}There are two fixes. You can return a List<String> collected inside the block, or you can return the unclosed stream and document that the caller must close it. The first is safer. Also remember that a stream is single-use: after one terminal operation, a second one throws IllegalStateException. Open a new stream if you need a second pass.
Files.lines or a BufferedReader?
Both read lazily. Files.lines fits when your logic is a pipeline of filters and maps. A BufferedReader loop fits when you need more control:
- You must handle the line number, or state carried from one line to the next.
- You want a checked exception from your own code without wrapping.
- You are writing the output line by line at the same time, as in the upper-case copy example from the buffered I/O chapter.
Parallel streams rarely help here. Reading a file is usually limited by disk or network speed rather than by the CPU. Add .parallel() only after measuring a CPU-heavy per-line step, and expect the output order of forEach to change.
Edge cases
- Line terminators. Lines end at
\n,\ror\r\n. The terminators are not part of the returned strings. - Final empty line. A file ending in a newline does not produce an extra empty element. A file with a blank line in the middle does produce an empty string there.
- File changes during reading. If another process modifies the file while you read it, the result is unspecified. Use a copy or a snapshot if you need consistency.
- Very long lines. Each line is held fully in memory. A file with no newlines is a single huge
String, so streaming does not help.
Exercise
Write a method that returns the number of lines in a file that contain the word "TODO", without loading the file into memory. Which exceptions must your code deal with, and when can each occur?
Show answer
Use a stream inside try-with-resources: static long countTodos(Path file) throws IOException { try (Stream<String> lines = Files.lines(file)) { return lines.filter(l -> l.contains("TODO")).count(); } } A checked IOException (such as NoSuchFileException) can be thrown when Files.lines opens the file, before any line is read. An UncheckedIOException can be thrown by count() while the lines are read, for example when the file contains bytes that are not valid UTF-8. Its cause is the original IOException. The try-with-resources block closes the file in both cases.
Exercise
A colleague's method opens Files.lines, sorts the lines with sorted(), and prints the first five. The program runs out of memory on a 20 GB file. Why, and how would you change it?
Show answer
sorted() is a stateful operation that must buffer every line before it can emit the first one, so the whole file ends up in memory. If the goal is only to print the first five lines in file order, drop sorted() and use limit(5), which stops reading after five lines. If the goal is the five smallest lines, keep a bounded structure such as a PriorityQueue of size five and update it in forEach, so memory stays constant.