try-with-resources语句

时间:2020-04-16 15:33:20   收藏:0   阅读:69

在 JDK 7 之前,各种资源操作需要在finally里面手动关闭

1 static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
3     BufferedReader br = new BufferedReader(new FileReader(path));
4     try {
5         return br.readLine();
6     } finally {
7         if (br != null) br.close();
8     }
9 }

在JDK 7中引入try-with-resources。在引入try-with-resources后,JDK中IO相关操作都可以实现资源自动实现,不需要再finally再手动关闭。

try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时自动关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。

 1 public class Demo {    
 2     public static void main(String[] args) {
 3         try(Resource res = new Resource()) {
 4             res.doSome();
 5         } catch(Exception ex) {
 6             ex.printStackTrace();
 7         }
 8     }
 9 }
10 
11 class Resource implements AutoCloseable {
12     void doSome() {
13         System.out.println("do something");
14     }
15     @Override
16     public void close() throws Exception {
17         System.out.println("resource is closed");
18     }
19 }

运行结果为:

1 do something
2 resource is closed

可以看到,资源终止被自动关闭了。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!