【发布时间】:2014-02-04 22:11:32
【问题描述】:
我看到了这段代码,想知道为什么in.close() 是在finally block 中完成的。 try-with resources 的主要观点是它 closes 和 resources 是正确的。
File file = new File(FILE_NAME);
FileInputStream in = null;
try (in = new FileInputStream(file)){
//do something
} catch (final FileNotFoundException e) {
log.log(Level.WARNING, "file not found, " + file.getAbsolutePath(), e);
} catch (final IOException e) {
log.log(Level.WARNING, "cannot access the file for reading", e);
} finally {
if (in != null){
try {
in.close();
} catch (final IOException e) {
log.log(Level.WARNING, "Attempt to close file failed.", e);
}
}
}
会不会出现在Java中使用try-with-resources可以打开文件却无法关闭的情况?
【问题讨论】:
-
没有关闭
File这样的事情,您似乎正在关闭FileInputStream。 -
是的,这就是我的意思;关闭资源对吗?
标签: java exception finally try-with-resources