Java | 原来 try 还可以这样用啊?!

 

习惯了这样的try:

1 try
2 {
3 
4 } catch (Exception e)
5 {
6 }

 

看到了这样的try,觉得有点神奇:

1 try(...)
2 {
3 } catch (Exception e) 
4 {
5 }

 

原来这还有个专业术语, try-with-resources statement ,它会自动关闭括号内的资源(resources),不用手动添加代码   xx.close();  了。

 

看个小例子:

 1 package org.young.elearn;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 import org.junit.Test;
 7 
 8 /**
 9  * try-with-resources 的使用
10  * try(resouces)
11  * {
12  * 
13  * } catch (Exception e){}
14  * 
15  * 这里的resource会自动关闭
16  * 
17  * 1. resource 必须继承自 java.lang.AutoCloseable
18  * 2. 定义和赋值必须都在try里完成
19  * 
20  * 
21  *
22  * @author by Young.ZHU
23  *      on 2016年5月29日
24  *
25  * Package&FileName: org.young.elearn.TryWithResourcesTest
26  */
27 public class TryWithResourcesTest {
28     
29     /**
30      * 验证一下资源是不是真的关闭了
31      */
32     @Test
33     public void test() {
34 
35         try (MyResources mr = new MyResources()) {
36 //            mr.doSomething(4);
37             mr.doSomething(9);
38         } catch (Exception e) {
39             System.out.println(e.getMessage());
40         }
41     }
42     
43     /**
44      * 编译错误:
45      * The resource f of a try-with-resources statement cannot be assigned
46      */
47     @Test
48     public void test2() {
49         try (FileOutputStream f = null;) {
50 //            f = new FileOutputStream(new File(""));
51         } catch (IOException e) {
52             e.printStackTrace();
53         }
54     }
55 
56     /**
57      * 编译错误:
58      * The resource type File does not implement java.lang.AutoCloseable
59      */
60     @Test
61     public void test1() {
62         /*try (File file = new File("d:\\xx.txt");) {
63             
64         } */
65     }
66 
67 }
68 
69 class MyResources implements AutoCloseable {
70 
71     @Override
72     public void close() throws Exception {
73         System.out.println("resources are closed.");
74     }
75     
76     public void doSomething(int num) throws Exception {
77         if (num % 2 == 0) {
78             System.out.println("it's OK.");
79         } else {
80             throw new Exception("Enter an even.");
81         }
82     }
83 }

 

以后使用 InputStream,OutputStream 之类的就方便一点了,具体可参考另一个例子:GitHub

 

 阅读原文

posted on 2016-06-01 21:42  Memory4Young  阅读(7674)  评论(0编辑  收藏  举报

导航