在早前一段时间接触到这个特性,当时觉得没什么大不了的(主要是当时不了解),可能是自己当初看的时候没辣么仔细吧!哈哈,现在重新接触感觉挺不错的,特此记录下来
在java6之前我们的资源管理语法模式大概是这样的:
byte[] buf = new byte[1024];
FileInputStream fin = null;
FileOutputStream fout = null;
try {
//资源操作
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
int i = fin.read(buf, 0, 1024);
while(i != -1) {
fout.write(buf, 0, i);
i = fin.read(buf, 0, 1024);
}
} catch (Exception e) {
//异常处理
e.printStackTrace();
} finally {
//资源释放
try {
fin.close();
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
现在在java7中,我们可以这样写了:
byte[] buf = new byte[1024];
try (FileInputStream fin = new FileInputStream(args[0]);
FileOutputStream fout = new FileOutputStream(args[1])
){
//异常处理
int i = fin.read(buf, 0, 1024);
while(i != -1) {
fout.write(buf, 0, i);
i = fin.read(buf, 0, 1024);
}
} catch (Exception e) {
e.printStackTrace();
}
}
看了上面的代码会不会觉的很清晰,也觉得很cool,反正我是觉得很cool了。
在java7中,放在try括号里的资源会在try执行完毕后自动关闭,这样减少了我们编写错误代码的几率了,因为我们在处理资源的时候难免发生错误。而且资源的各种组合错误很让人头疼的。不过,使用这个新特性的时候有几点要注意:
1. 在TWR的try从句中的出现的资源必须实现AutoCloseable接口的, 在java7中,大多数资源都被修改过了,可以放心使用
2. 在某些情况下资源可能无法关闭,比如
FileReader reader = new FileReader(new File("c:\\test.txt"));
当new File出错时,FileReader就可能关闭不了,所以正确的做法是为各个资源声明独立变量
最后,推荐一篇博文 http://www.oschina.net/question/12_10706,也是讲这个新特性的