最近项目中经常遇到没有关闭流的情况,领导要求所有人都检查一遍代码,做好处理。我的代码按照try with resource语法进行改造,结果领导质疑这样做的可行性?够了,话不多说,我编译下看看事实——
java代码如下,FilwSystem的获取放在try后的( )中。
public void demo2() {
try (
FileSystem fileSystem = getFileSystem();
){
fileSystem.getRootDirectories();
fileSystem.getFileStores();
}catch (Exception e){
e.printStackTrace();
}
}
把整个工程install以后,找到对应的class,看到这段代码编译出来是这个样子的:
public void demo2() {
try {
FileSystem fileSystem = this.getFileSystem();
Throwable var2 = null;
try {
fileSystem.getRootDirectories();
fileSystem.getFileStores();
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if (fileSystem != null) {
if (var2 != null) {
try {
fileSystem.close();
} catch (Throwable var11) {
var2.addSuppressed(var11);
}
} else {
fileSystem.close();
}
}
}
} catch (Exception var14) {
var14.printStackTrace();
}
}
可以看出,编译后的文件照样是中规中矩地在finally中关闭了流,但是按照上述方法,代码就显得比较优雅,也避免了每次去finally块中又加了try-catch块,可能还忘掉的情况。
备注,这是JDK1.7的新东西。而且,try里的对象要实现AutoCloseable接口,这样才会在使用完成后自动去调用close()方法。