Java之Java7新特性之try资源句式

时间:2023-03-09 22:07:05
Java之Java7新特性之try资源句式

一、原来写法:

 static String readFirstLineFromFile(String path) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(path));
} catch (Exception ex) {
//do exception action
} finally {
if (br != null) {
try {
br.close();
} catch (Exception ex) {
//do exception action
}
}
}
}

二、新写法:

 static String readFirstLineFromFile(String path) throws IOException {
try(
BufferedReader br = new BufferedReader(new FileReader(path))
){
return br.readLine();
} catch (Exception ex) {
//do exception action
}
}

三、备注:

1、新写法的代码更简洁清晰,从原来的16行代码减少到9行代码;

2、新写法是JDK 1.7及后续版本才支持的,在JDK 1.7版本以前是不支持的,并且try 里面的资源必须实现java.lang.AutoCloseable接口,这样它将被自动关闭,无论是程序正常结束还是中途抛出异常。