關于Java中的try-with-resources語句
介紹
try-with-resources是Java中的環(huán)繞語句之一,旨在減輕開發(fā)人員釋放try
塊中使用的資源的義務。
它最初在Java 7中引入,背后的全部想法是,開發(fā)人員無需擔心僅在一個try-catch-finally塊中使用的資源的資源管理。這是通過消除對finally
塊的依賴而實現(xiàn)的。
此外,使用try-with-resources的代碼通常更清晰易讀,因此使代碼更易于管理,尤其是當我們處理許多try
塊時。
語法
try-with-resources的語法與通常try-catch-finally語法相同。
普通try:
BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(fileName)); writer.write(str); // do something with the file we've opened } catch (IOException e) { // handle the exception } finally { try { if (writer != null) writer.close(); } catch (IOException e) { // handle the exception } }
try-with-resources:
try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))){ writer.write(str); // do something with the file we've opened } catch(IOException e){ // handle the exception }
Java理解此代碼的方式:
try語句之后在括號中打開的資源僅在此處和現(xiàn)在需要。
.close()
在try塊中完成工作后,將立即調(diào)用它們的方法。如果在try塊中拋出異常,無論如何我會關閉這些資源。
注意:
從Java 9開始,沒有必要在try-with-resources語句中聲明資源。
可以這樣做:
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); try (writer) { writer.write(str); // do something with the file we've opened } catch(IOException e) { // handle the exception }
到此這篇關于關于Java中的try-with-resources語句的文章就介紹到這了,更多相關Java try-with-resources語句內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot項目使用mybatis-plus逆向自動生成全套代碼
在JavaWeb工程中,每一個SSM新項目或者說是SpringBoot項目也好,都少不了model、controller、service、dao等層次的構建。使用mybatis-plus逆向可以自動生成,感興趣的可以了解一下2021-09-09基于Spring Data Jest的Elasticsearch數(shù)據(jù)統(tǒng)計示例
本篇文章主要介紹了基于Spring Data Jest的Elasticsearch數(shù)據(jù)統(tǒng)計示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02