What is the problem in the following code?

Description:

final Path path = Paths.get(...);

Files.lines(path).forEach(System.out::println);

Solution:

The problem is that the Stream returned by Files.lines() is not closed.

This should be used instead:

try (
    final Stream<String> stream = Files.lines(path);
) {
    stream.forEach(System.out::println);
}

Stream extends BaseStream, and BaseStream extends AutoCloseable. While this has no influence on streams you obtain from collections for instance, the stream returned by Files.lines() is I/O bound. Neglecting to close it correctly may lead to a resource leak in the event of an error occurring while processing the stream.

0 answers