Java 7中自動關閉流和catch多個異常__Java

來源:互聯網
上載者:User

在我們平時的開發工作中, 經常需要讀寫流,在這個過程最讓人蛋疼的就是各種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多個異常也使得代碼更加的簡潔。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.