Does below code need to be wrapped in try-with-resources to make sure underlying file is closed?
List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList());
Does below code need to be wrapped in try-with-resources to make sure underlying file is closed?
List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList());
As the javadoc of the overloaded
Files#lines(Path, Charset)
method statesSo yes, wrap the
Stream
returned bylines
in atry-with-resources
statement. (Or close it appropriately.)There is a trick to make the
Stream
implementation callingclose()
after the terminal operation:It simply creates a stream encapsulating the stream of lines as a single item and uses
flatMap
with an identity function (Function.identity()
would work as well) to turn it into a stream of lines again.The interesting point is a property of
Stream.flatMap(…)
:So the code above will close the stream of lines. While it looks more concise it has the disadvantage over try with resources that current implementation of
flatMap
lacks lazy evaluation which is not relevant here as you are collecting all lines into a list anyway. But it’s something to keep in mind when using this trick in other scenarios.For the question’s code as-is there is an even simpler solution:
Reads all lines and closes all resources…