今天擼代碼的時候發現了一段這樣的代碼
try( Connection conn=DriverManager.getConnection(url,user,pass); Statement stmt=conn.createStatement() ) { boolean hasResultSet=stmt.execute(sql); }
和平常見的不一樣,我們平常見的是這樣的
try{ fis=new FileInputStream("src\\com\\ggp\\first\\FileInputStreamDemo.java"); byte[]bbuf=new byte[1024]; int hasRead=0; while((hasRead=fis.read(bbuf))>0){ System.out.println(new String(bbuf,0,hasRead)); } }catch(IOException e){ e.printStackTrace(); }finally{ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
如果{}中的代碼塊出現了異常,會被catch捕獲,然后執行catch中的代碼,接着執行finally中的碼,其中catch中的代碼有了異常才會被執行,finally中的代碼無論有沒有異常都會被執行,
而第一種情況的()中的代碼一般放的是對資源的申請,如果{}中的代碼出項了異常,()中的資源就會被關閉,這在inputstream和outputstream的使用中會很方便例如
private static void customBufferStreamCopy(File source, File target) { try (InputStream fis = new FileInputStream(source); OutputStream fos = new FileOutputStream(target)){ byte[] buf = new byte[8192]; int i; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } } catch (Exception e) { e.printStackTrace(); } }
從網上查閱資料得知從 Java 7 build 105 版本開始,Java 7 的編譯器和運行環境支持新的 try-with-resources 語句,稱為 ARM 塊(Automatic Resource Management) ,自動資源管理。
The try
-with-resources statement is a try
statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try
-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
, can be used as a resource.
帶有resources的try語句聲明一個或多個resources。resources是在程序結束后默認掉resources.close(),關閉的資源對象。try-with-resources語句確保在語句末尾關閉每個resources。任何實現java.lang.AutoCloseable,包括實現了java.io.Closeable的類,都可以
作為resources使用