Java 7 的編譯器和運行環境支持新的 try-with-resources 語句,稱為 ARM 塊(Automatic Resource Management) ,自動資源管理。
新的語句支持包括流以及任何可關閉的資源,例如,一般我們會編寫如下代碼來釋放資源:
public static void filyCopy(File one,File two){ FileInputStream fileInput = null; FileOutputStream fileOutput = null; try { fileInput = new FileInputStream(one); fileOutput = new FileOutputStream(two); byte[] b = new byte[1024]; int len = 0; while((len = fileInput.read(b)) != -1){ fileOutput.write(b, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally {//釋放資源 try { if(fileInput != null){ fileInput.close(); } if(fileOutput != null){ fileOutput.close(); } } catch (Exception e2) { e2.printStackTrace(); } } }
使用 try-with-resources 語句來簡化代碼如下:
public static void filyCopy2(File one,File two){ try (FileInputStream fileInput = new FileInputStream(one); FileOutputStream fileOutput = new FileOutputStream(two);){ byte[] b = new byte[1024]; int len = 0; while((len = fileInput.read(b)) != -1){ fileOutput.write(b, 0, len); } } catch (Exception e) { e.printStackTrace(); } }
在這個例子中,數據流會在 try 執行完畢后自動被關閉,前提是,這些可關閉的資源必須實現 java.lang.AutoCloseable 接口。
