java try(){}catch(){}自動資源釋放
**從 Java 7 build 105 版本開始,Java 7 的編譯器和運行環境支持新的 try-with-resources 語句,稱爲 ARM 塊(Automatic Resource Management) ,自動資源管理。
使用try(){}catch(){}效果:
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();
}
}
在這個例子中,數據流會在 try 執行完畢後自動被關閉,前提是,這些可關閉的資源必須實現 java.lang.AutoCloseable 接口。**