gpt4 book ai didi

java - 如何在 Java 中关闭隐式流?

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:35 25 4
gpt4 key购买 nike

Files.walk 是我应该关闭的流之一,但是,如何在如下代码中关闭流?下面的代码是否有效,或者我是否需要重写它以便我可以访问流以关闭它?

List<Path> filesList = Files.walk(Paths.get(path)).filter(Files::isRegularFile ).collect(Collectors.toList());

最佳答案

您应该将它与 try-with-resource 一起使用:

try(Stream<Path> path = Files.walk(Paths.get(""))) {
List<Path> fileList = path.filter(Files::isRegularFile)
.collect(Collectors.toList());
}

Files.walkapiNote 明确地读到:

This method must be used within a try-with-resources statement or similar
control structure to ensure that the stream's open directories are closed
promptly after the stream's operations have completed.

关于java - 如何在 Java 中关闭隐式流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54096143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com