您的位置:首页 > 编程语言 > Java开发

java7新特性:Try - with - Resources语句

2013-10-22 21:06 399 查看
在此之间我们处理SQL语句,异常或IO对象时,不得不用命令关闭资源,就如下:

try{

//Create a resource- R

} catch(SomeException e){

//Handle the exception

} finally{

//if resource R is not null then

try{

//close the resource

}

catch(SomeOtherException ex){

}

}
这样写出来不免看起来比较繁琐,有没有什么办法在确保了每个资源都在语句使用后被关闭?
答案是:Try-with-resources

因为Try-with-resources语句确保了每个资源都在语句使用后被关闭。任何部署java.lang
AutoCloseable或java.io.Closeable 界面的对象都可当做资源使用。

如下所示的代码:

private static void customBufferStreamCopy(File source, File target) {
try (InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target)){

byte[] buf = new byte[8192];

int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: