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 接口。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM