Java使用 try-with-resources 實(shí)現(xiàn)自動(dòng)關(guān)閉資源的方法
1、 在Java1.7之前,我們需要通過下面這種方法, 在finally中釋放資源,這種方法有點(diǎn)繁瑣。
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實(shí)現(xiàn)自動(dòng)關(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)程序運(yùn)行完離開try語句塊時(shí),( )里的資源就會(huì)被自動(dòng)關(guān)閉。
但是try-with-resources還有幾個(gè)關(guān)鍵點(diǎn)要記住:
①、try()里面的類,必須實(shí)現(xiàn)了AutoCloseable接口。②、在try()代碼中聲明的資源被隱式聲明為fianl。③、使用分號(hào)分隔,可以聲明多個(gè)資源。
3、自定義類并實(shí)現(xiàn)AutoCloseable接口
class TestAutoClosable implements AutoCloseable { @Override public void close() throws Exception { System.out.println('close'); } public void test() { System.out.println('test'); } }
接下來我們測(cè)試下,我們寫得自定義類
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()方法時(shí),下面是控制臺(tái)打印的:
testclose
可以看到資源被成功關(guān)閉。
到此這篇關(guān)于Java使用 try-with-resources 實(shí)現(xiàn)自動(dòng)關(guān)閉資源的方法的文章就介紹到這了,更多相關(guān)java 自動(dòng)關(guān)閉資源內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python 如何停止一個(gè)死循環(huán)的線程3. Python編寫nmap掃描工具4. 如何基于python3和Vue實(shí)現(xiàn)AES數(shù)據(jù)加密5. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總6. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值7. 關(guān)于HTML5的img標(biāo)簽8. Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送9. python 爬取嗶哩嗶哩up主信息和投稿視頻10. php5.6不能擴(kuò)展redis.so的解決方法
