Java使用 try-with-resources 實現(xiàn)自動關(guā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)自動關(guān)閉資源
try (BufferedReader br = new BufferedReader(new FileReader(''))) { while ((str = br.readLine()) != null) {System.out.println(str); } } catch (IOException e) { e.printStackTrace(); }
這樣看上去,是不是感覺代碼干凈了許多,當(dāng)程序運行完離開try語句塊時,( )里的資源就會被自動關(guān)閉。
但是try-with-resources還有幾個關(guān)鍵點要記住:
①、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(); }
當(dāng)調(diào)用testAutoClosable.test()方法時,下面是控制臺打印的:
testclose
可以看到資源被成功關(guān)閉。
到此這篇關(guān)于Java使用 try-with-resources 實現(xiàn)自動關(guān)閉資源的方法的文章就介紹到這了,更多相關(guān)java 自動關(guān)閉資源內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. idea不能自動補全yml配置文件的原因分析2. 教你如何寫出可維護的JS代碼3. CSS可以做的幾個令你嘆為觀止的實例分享4. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)5. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)6. 利用ajax+php實現(xiàn)商品價格計算7. Vue的Options用法說明8. css代碼優(yōu)化的12個技巧9. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法10. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?
