今天偶然發現java的try catch盡然有了c#中using的做用,忽然發現本身沒有跟上java的步伐了,今天就轉一篇@紅薯的文章,省得之後用的時候又找不到了。java
從 Java 7 build 105 版本開始,Java 7 的編譯器和運行環境支持新的 try-with-resources 語句,稱爲 ARM 塊(Automatic Resource Management) ,自動資源管理。c#
新的語句支持包括流以及任何可關閉的資源,例如,通常咱們會編寫以下代碼來釋放資源:ui
private static void customBufferStreamCopy(File source, File target) { //在最後不用再finally中釋放資源了,能這樣寫的前提是要自動釋放資源的類必須實現java.lang.AutoCloseable 接 //口 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); } } //也能夠處理多個異常eg: //catch (IoException | NullPointerException) catch (Exception e) { e.printStackTrace(); } }
之後要多用了。spa