一、原来写法:
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 action 13 } 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 action 8 } 9 }
三、备注:
1、新写法的代码更简洁清晰,从原来的16行代码减少到9行代码;
2、新写法是JDK 1.7及后续版本才支持的,在JDK 1.7版本以前是不支持的,并且try 里面的资源必须实现java.lang.AutoCloseable接口,这样它将被自动关闭,无论是程序正常结束还是中途抛出异常。