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

 

 閱讀原文


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM