java6中的资源管理语法
InputStream is = null;
try {
is = url.openStream();
OutputStream out = new FileOutputStream();
try {
byte[] buf = new byte[4096];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
} finally {
try {
out.close();
} catch (IOException closeOutx){
}
}
} catch (FileNotFoundException fnfx) {
} catch (IOException openx){
} finally {
try {
if (is != null) is.close();
} catch (IOException closeInx){
}
}
让我们看看上面的代码用Java7写出来什么样。和上面一样,url是一个指向下载目标文件的URL对象,file是一个保存下载数据的File对象。
try(OutputStream out = new FileOutputStream(file);
InputStream is = url.openStream() ) {
byte[] buf = new byte[4096];
int len;
while((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
这是资源自动化管理代码块的基本形式——把资源放在try的圆括号内,在这段代码块中使用的资源在处理完成后会自动关闭。
但使用try-with-resources特性时还是要小心,因为在某些情况下资源可能无法关闭。比如在下面的代码中,如果从文件(sonmeFile.bin)创建ObjectInputStream时出错,FileInputStream就可能无法正确关闭。
try(ObjectInputStream in = new ObjectInputStream(new
FileInputStream("someFile.bin")) ) {
...
}
假定文件(someFIle.bin)存在,但可能不是ObjectInput类型的文件,所以文件无法正确打开。因此不能构建ObjectInputStream,所以FileInputStream也没办法关闭。
要确保twr生效,正确的用法是为各个资源声明独立变量。
try(FIleINputStream fin = new FileInputStream("someFIle.bin");
ObjectInputStream in = new ObjectInputStream(fin) ) {
...
}
目前TWR特性依靠一个新定义的接口实现AutoCloseable。TWR的try从句中出现的资源类都必须实现这个接口。Java7平台中的大多数资源类都被修改过,已经实现了AutoCloseable(Java7还定义了其父接口Closeable),但并不是全部资源相关的类都采用了这项技术。不过JDBC4.1已经具备了这个特性。
然而在自己的代码里,在处理资源时一定要用TWR,从而避免在异常处理时出现bug。