What is the problem in the following code?


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



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 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