使用 java 的 java.nio.file.readAllLines 时是否需要使用 try-with-resource?
Do I need to use a try-with-resource when using java's java.nio.file.readAllLines?
使用java.nio.file.readAllLines时,是否需要关闭资源?
我在网上看到一些例子,他们不这样做。
例如这里https://www.programcreek.com/java-api-examples/?class=java.nio.file.Files&method=readAllLines
他们捕捉到 IOException 但他们没有关闭任何资源。
任何帮助将不胜感激,谢谢!
在 Files class 'readAllLines(path)' 方法中抛出 'IOException' 在某些情况下它会抛出异常,您可以在此处捕获异常并发送正确的错误消息以结束 user.Other明智的做法可能是您需要面对运行时问题。
Path Path = null;
try {
Files.readAllLines(Path);
}catch (IOException e) {
//write your error message logic
}
TL;DR: 没有。
正如 Turing85 在评论中暗示的那样,它在文档中。
您链接到的示例使用的是单参数 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.nio.file.readAllLines时,是否需要关闭资源?
我在网上看到一些例子,他们不这样做。
例如这里https://www.programcreek.com/java-api-examples/?class=java.nio.file.Files&method=readAllLines 他们捕捉到 IOException 但他们没有关闭任何资源。
任何帮助将不胜感激,谢谢!
在 Files class 'readAllLines(path)' 方法中抛出 'IOException' 在某些情况下它会抛出异常,您可以在此处捕获异常并发送正确的错误消息以结束 user.Other明智的做法可能是您需要面对运行时问题。
Path Path = null;
try {
Files.readAllLines(Path);
}catch (IOException e) {
//write your error message logic
}
TL;DR: 没有。
正如 Turing85 在评论中暗示的那样,它在文档中。
您链接到的示例使用的是单参数 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.
所以不,您不需要执行任何操作来关闭文件或其他资源。因此,您阅读的示例在这一点上是完整且正确的。
文档链接