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 界面的对象都可当做资源使用。
如下所示的代码:
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(); } }
相关文章推荐
- Java7 新特性:try() 语句 即 try-with-resources
- Java SE7新特性之try-with-resources语句
- Java SE7新特性之try-with-resources语句
- Java7新的try-with-resources语句,自动资源释放
- Java SE7新特性之try-with-resources语句
- java7特性之 try-with-resources
- Java 7 新特性try-with-resources语句
- Java新特性之try-with-resources语句
- Java SE7新特性之try-with-resources语句
- Java7新特性--try-with-resources,自动关闭资源
- Java SE7新特性之try-with-resources语句
- java7新特性之Try-with-resources (TWR)
- Java SE7新特性之try-with-resources语句
- JDK1.7新特性-try-with-resources语句
- Java7提供了简化关闭资源的try语句:try-with-resources自动关闭资源的try语句
- Java7之try-with-resources语句
- Java SE7新特性之try-with-resources语句
- Java SE7新特性之try-with-resources语句
- Java SE7新特性之try-with-resources语句
- Java SE7新特性之try-with-resources语句