Video in progress
What do you pay attention to when reading a large file with Files.lines()?
Files.lines reads the file lazily, line by line, so memory is saved even on a large file. But it holds an open file descriptor, so you must close the stream with try-with-resources. A read error surfaces as an UncheckedIOException.
📖 Answer
try (Stream<String> lines = Files.lines(Path.of("access.log"))) {
Map<String, Long> byStatus = lines
.filter(l -> !l.isBlank())
.map(l -> l.split(" ")[8])
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
}
What to watch for:
- Closing. Most streams (
list.stream()) don't require closing, but the ones tied to IO (Files.lines,Files.list,Files.walk) do. If you don't close it, the service eventually fails with "Too many open files". A terminal operation doesn't close the stream automatically. - Don't return the stream from a method. The method that opened the file should close it. If you have to return it, state clearly that closing is the caller's responsibility.
- Encoding. The default is UTF-8. If the file is in a different encoding, you get a
MalformedInputException; pass it explicitly withFiles.lines(path, charset). - Errors. An
IOExceptionduring reading is wrapped in anUncheckedIOExceptioninside the stream, so don't forget to catch it. Files.readAllLinesloads every line into memory at once. On a file of several gigabytes that is anOutOfMemoryError.
Through onClose(...) you can also release extra resources when the stream is closed.
Sign up to mark studied questions and save your progress.