编程语言
首页 > 编程语言> > java – Stream上的collect操作是否关闭流和底层资源?

java – Stream上的collect操作是否关闭流和底层资源?

作者:互联网

以下代码是否需要包含在try-with-resources中以确保底层文件已关闭?

List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList());

解决方法:

正如重载Files#lines(Path, Charset)方法的javadoc所述

The returned stream encapsulates a Reader. If timely disposal of file
system resources is required, the try-with-resources construct should
be used to ensure that the stream’s close method is invoked after the
stream operations are completed.

所以是的,在try-with-resources语句中包装由行返回的Stream. (或适当的close.)

标签:java,java-8,java-stream,file-io,try-with-resources
来源: https://codeday.me/bug/20190927/1822810.html