抱歉,您的瀏覽器無法訪問本站
本頁面需要瀏覽器支持(啟用)JavaScript
了解詳情 >

java7之前

在java7版本之前我们使用资源后,都需要把资源关闭,在try-catch-finally中的finally关闭资源。

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
long currentTime = System.currentTimeMillis();
BufferedReader bufferedReader = null;
try{
bufferedReader = new BufferedReader(new FileReader("C:/Users/ZJ/Desktop/spring.log"));
String line = null;
while((line = bufferedReader.readLine())!=null){
System.out.println(line);
}
System.out.println((System.currentTimeMillis()-currentTime)/1000.0+"秒");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

这个代码莫得问题,但是太杂乱了,因此java7提供了一个新的语法糖:try-with-resource。

java7以后

try-with-resources 方式来管理资源,在try中声明资源,当程序执行完后,会自动将声明的资源关闭掉

例子

1
2
3
4
5
6
7
8
9
10
11
12
long currentTime = System.currentTimeMillis();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader("C:/Users/ZJ/Desktop/spring.log"))){
String line = null;
while((line = bufferedReader.readLine())!=null){
System.out.println(line);
}
System.out.println((System.currentTimeMillis()-currentTime)/1000.0+"秒");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

我们可以很明显的看到代码量少了很多,而且再也不会因为忘记close而导致出问题拉。