对于IO资源,网络连接等资源的使用,在结束后往往需要close,JAVA7之前都是自己在finally中close
java7 提供了新功能,可以有jdk来close,即把资源放在try()后面的括号里声明处理
例子:
try (FileOutputStream fos = new FileOutputStream(destinationFile, false)) {
properties.store(fos, "New copied configuration");
LOGGER.info("创建 destination file成功,位于" + destinationFile.getAbsolutePath());
} catch (Exception e) {
LOGGER.error("不能创建 destination file " + destinationFile.getName());
throw new NongfuException("不能创建 destination file " + destinationFile.getName(), e);
}
如果有多个资源,则可以用;分割语句
Java7自动关闭资源
本文介绍Java7新增功能,允许开发者直接在try语句中声明并自动关闭资源,避免了手动在finally块中关闭资源的繁琐操作。示例展示了如何使用此特性安全地创建文件。
170万+

被折叠的 条评论
为什么被折叠?



