⼀、原来写法:
1 static String readFirstLineFromFile(String path) throws IOException { 2 BufferedReader br = null; 3 try {
4 br = new BufferedReader(new FileReader(path)); 5 } catch (Exception ex) { 6 //do exception action 7 } finally {
8 if (br != null) { 9 try {
10 br.close();
11 } catch (Exception ex) {12 //do exception action13 }14 }15 }16 }
⼆、新写法:
1 static String readFirstLineFromFile(String path) throws IOException { 2 try(
3 BufferedReader br = new BufferedReader(new FileReader(path)) 4 ){
5 return br.readLine(); 6 } catch (Exception ex) {7 //do exception action8 }9 }
三、备注:
1、新写法的代码更简洁清晰,从原来的16⾏代码减少到9⾏代码;
2、新写法是JDK 1.7及后续版本才⽀持的,在JDK 1.7版本以前是不⽀持的,并且try ⾥⾯的资源必须实现java.lang.AutoCloseable接⼝,这样它将被⾃动关闭,⽆论是程序正常结束还是中途抛出异常。
因篇幅问题不能全部显示,请点此查看更多更全内容