Happyjava's blog site

Happyjava's blog site,分享编程知识,顺便发发牢骚

0%

你是否还在写try-catch-finally?来使用try-with-resources优雅地关闭流吧

前言

开发中,我们常常需要在最后进行一些资源的关闭。比如读写文件流等,常见的,我们会在最后的finally里进行资源的关闭。但是这种写法是很不简洁的。其实,早在JDK1.7就已经引入了try-with-resources来关闭资源的方式,我们今天就来体验一下try-with-resources的简洁之处。

旧版关闭资源的一些例子

在旧版的写法中(其实现在还有很多程序员是这么写的),资源都放在finally块里进行关闭,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void test4() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("D:\\head.jpg");
// do something
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

这种写法的麻烦之处在于,我们需要在finally块中关闭资源,所以inputStream只能定义在try块的外面。关闭之前,还需要做一步判空,避免因为inputStream为空而导致的空指针异常。这种写法是很繁琐的。

try-with-resources

同样的功能,如果采用try-with-resources,就会使代码变得非常简洁:

1
2
3
4
5
6
7
8
9
@Test
public void test5() {
try (InputStream inputStream = new FileInputStream("D:\\head.jpg")) {
byte[] bytes = inputStream.readAllBytes();
// do something
} catch (IOException e) {
e.printStackTrace();
}
}

try-with-resources的用法就是,在try关键字的后面跟一个括号,把需要关闭的资源定义在括号内。在try块执行完之后会自动的释放掉资源。

什么资源可以被try-with-resources自动关闭

并不是所有资源都可以被try-with-resources自动关闭的,只有实现了java.lang.AutoCloseable接口的类,才可以被自动关闭。如果没有实现java.lang.AutoCloseable的类定义在try的括号内,则会在编译器就报错。

如,自定义一个类MyResource,定义在括号内则会报错:提示需要java.lang.AutoCloseable的类。

自定义可以被自动关闭的类

我们也可以把自己的类编写为可以被try-with-resources自动关闭的类,只需要我们去实现java.lang.AutoCloseable接口即可。

1
2
3
4
5
6
7
class MyResource implements java.lang.AutoCloseable {

@Override
public void close() {
System.out.println("调用了close方法");
}
}
1
2
3
4
5
6
7
8
9
10
@Test
public void test5() {
try (InputStream inputStream = new FileInputStream("D:\\head.jpg");
MyResource myResource = new MyResource()) {
byte[] bytes = inputStream.readAllBytes();
// do something
} catch (IOException e) {
e.printStackTrace();
}
}

执行之后,会输出“调用了close方法”

总结

try-with-resources可以使代码更加简洁而且不容易出错。相比传统的try-catch-finally的写法,显然try-with-resources优点更多,至少不会存在finally关闭资源因为没判空而导致空指针的问题。