Does collect operation on Stream close the stream and underlying resources?

前端 未结 2 1201
萌比男神i
萌比男神i 2020-12-05 10:42

Does below code need to be wrapped in try-with-resources to make sure underlying file is closed?

List rows = Files.lines(inputFilePath).collect         


        
2条回答
  •  心在旅途
    2020-12-05 11:38

    There is a trick to make the Stream implementation calling close() after the terminal operation:

    List rows = Stream.of(Files.lines(inputFilePath)).flatMap(s->s)
                       .collect(Collectors.toList());
    

    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(…):

    Each mapped stream is closed after its contents have been placed into this stream.

    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:

    List rows = Files.readAllLines(inputFilePath);
    

    Reads all lines and closes all resources…

提交回复
热议问题