使用java.nio.file.readAllLines时,是否需要关闭资源?
我在网上看到一些例子,他们没有这样做。
例如这里https://www.programcreek.com/java-api-examples/?class=java.nio.file.Files&method=readAllLines 他们捕获 IOException 但不关闭任何资源。
如有任何帮助,我们将不胜感激,谢谢!
最佳答案
TL;DR:没有。
正如 Turing85 在评论中暗示的那样,它在文档中。
您链接到的示例使用 one-arg Files.readAllLines()
。该方法的文档说:
This method works as if invoking it were equivalent to evaluating the expression:
Files.readAllLines(path, StandardCharsets.UTF_8)
这里提到的两个参数方法的文档说:
This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
所以不,您无需执行任何操作来关闭文件或其他资源。因此,您阅读的示例在这一点上是完整且正确的。
文档链接
关于java - 使用java的java.nio.file.readAllLines时是否需要使用try-with-resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486837/