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

习惯了这样的try:

1
2
3
4
5
6
try
{

} catch (Exception e)
{
}

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

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

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

看个小例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package org.young.elearn;

import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;

/**
 * try-with-resources 的使用
 * try(resouces)
 * {
 * 
 * } catch (Exception e){}
 * 
 * 这里的resource会自动关闭
 * 
 * 1. resource 必须继承自 java.lang.AutoCloseable
 * 2. 定义和赋值必须都在try里完成
 *
 * @author by Young.ZHU
 *      on 2016年5月29日
 *
 * Package&FileName: org.young.elearn.TryWithResourcesTest
 */
public class TryWithResourcesTest {

/**
 * 验证一下资源是不是真的关闭了
 */
@Test
public void test() {

try (MyResources mr = new MyResources()) {
//mr.doSomething(4);
mr.doSomething(9);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

/**
 * 编译错误:
 * The resource f of a try-with-resources statement cannot be assigned
 */
@Test
public void test2() {
try (FileOutputStream f = null;) {
//f = new FileOutputStream(new File(""));
} catch (IOException e) {
e.printStackTrace();
}
}

/**
 * 编译错误:
 * The resource type File does not implement java.lang.AutoCloseable
 */
@Test
public void test1() {
/*try (File file = new File("d:\\xx.txt");) {

} */
}

}

class MyResources implements AutoCloseable {

@Override
public void close() throws Exception {
System.out.println("resources are closed.");
}

public void doSomething(int num) throws Exception {
if (num % 2 == 0) {
System.out.println("it's OK.");
} else {
throw new Exception("Enter an even.");
}
}
}

 

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

注:要求JDK 7 以上

加入讨论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据