Java使用 try-with-resources 實現(xiàn)自動關閉資源的方法
1、 在Java1.7之前,我們需要通過下面這種方法, 在finally中釋放資源,這種方法有點繁瑣。
BufferedReader br = null;
String str;
try {
br = new BufferedReader(new FileReader(""));
while ((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、在java1.7之后,可以使用try-with-resources實現(xiàn)自動關閉資源
try (BufferedReader br = new BufferedReader(new FileReader(""))) {
while ((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
這樣看上去,是不是感覺代碼干凈了許多,當程序運行完離開try語句塊時,( )里的資源就會被自動關閉。
但是try-with-resources還有幾個關鍵點要記?。?br />
①、try()里面的類,必須實現(xiàn)了AutoCloseable接口。
②、在try()代碼中聲明的資源被隱式聲明為fianl。
③、使用分號分隔,可以聲明多個資源。
3、自定義類并實現(xiàn)AutoCloseable接口
class TestAutoClosable implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("close");
}
public void test() {
System.out.println("test");
}
}
接下來我們測試下,我們寫得自定義類
try (BufferedReader br = new BufferedReader(new FileReader("E:/test.txt"));
TestAutoClosable testAutoClosable = new TestAutoClosable()) {
testAutoClosable.test();
} catch (Exception e) {
e.printStackTrace();
}
當調用testAutoClosable.test()方法時,下面是控制臺打印的:
test
close
可以看到資源被成功關閉。
到此這篇關于Java使用 try-with-resources 實現(xiàn)自動關閉資源的方法的文章就介紹到這了,更多相關java 自動關閉資源內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解析java稀疏數(shù)組如何幫助我們節(jié)省內存提升性能
這篇文章主要為大家介紹了java稀疏數(shù)組如何幫助我們節(jié)省內存提升性能解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
Spring使用@Value注解與@PropertySource注解加載配置文件操作
這篇文章主要介紹了Spring使用@Value注解與@PropertySource注解加載配置文件操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
Spring事務注解如何確保你的應用數(shù)據(jù)的一致性
Spring事務注解用于確保電商平臺下單過程中數(shù)據(jù)一致性,通過ACID原則、傳播行為、隔離級別和回滾配置管理數(shù)據(jù)庫操作,合理設置屬性及拆分事務方法可提升系統(tǒng)穩(wěn)定性與可靠性,本文介紹Spring事務注解如何確保你的應用數(shù)據(jù)的一致性,感興趣的朋友一起看看吧2025-07-07

