try with resource

##Java中关闭资源的正常方式& try with resource

Java中关闭资源的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//不正确的做法:
private void readTheFile() throws IOException {
Path path = Paths.get(this.fileName);
BufferedReader reader = Files.newBufferedReader(path, this.charset)) {
// ...
reader.close(); // Noncompliant
}
private void doSomething() {
OutputStream stream = null;
try {
for (String property : propertyList) {
stream = new FileOutputStream("myfile.txt"); // Noncompliant
// ...
}
} catch (Exception e) {
// ...
} finally {
stream.close();
}
}

在循环中打开了多个流,但是只有最后一个是被正确关闭的。

正确的做法:

1
2
3
4
5
6
7
8
9
10
11
12
private void readTheFile() throws IOException {
Path path = Paths.get(this.fileName);
BufferedReader reader = null;
try {
reader = Files.newBufferedReader(path, this.charset)) {
// ...
} finally {
if (reader != null) {
reader.close();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
private void doSomething() {
OutputStream stream = null;
try {
stream = new FileOutputStream("myfile.txt");
for (String property : propertyList) {
// ...
}
} catch (Exception e) {
// ...
} finally {
stream.close();
}
}

在Java7 中还有一种try with resource 的写法, 更紧凑一些, 可以通过try()请求资源,这个资源可以不用显示的声明关闭:

1
2
3
4
5
6
7
8
try(JedisPool pool = new JedisPool(
new JedisPoolConfig(),
"localhost")){
try (Jedis jedis = pool.getResource()) {
//...
}
pool.destroy();
}