在我們平時的開發工作中, 經常需要讀寫流,在這個過程最讓人蛋疼的就是各種try和catch, 然後到最後你還不能忘記關閉流,以免造成資源流失,這一整套下來感覺顯得特別的臃腫。下面是一個簡單的樣本 :
// 老的資源開啟檔案BufferedReader br = null;try {br = new BufferedReader(new FileReader("/Users/mrsimple/update_hosts.py"));StringBuilder sb = new StringBuilder();String line = "";while ((line = br.readLine()) != null) {sb.append(line).append("\n");}System.out.println(sb.toString());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (br != null) {try {br.close();} catch (IOException e) {e.printStackTrace();}}} // end of finaly
好在java 7 推出了兩項很實用的特性, 那就是流的自動關閉和catch多個異常。使用這兩個新特性後實現相同功能所需的代碼如下 :
// java 7中的資源開啟檔案try (BufferedReader newBr = new BufferedReader(new FileReader("/Users/mrsimple/update_hosts.py"))) {StringBuilder sb = new StringBuilder();String line = "";while ((line = newBr.readLine()) != null) {sb.append(line).append("\n");}System.out.println(sb.toString());} catch (IOException | FileNotFoundException e ) {e.printStackTrace();} 在try區塊中構建newBr對象,則該對象會在該區塊結束時自動關閉, 免去了開發人員手動關閉流。catch多個異常也使得代碼更加的簡潔。