Java中的自動資源管理


自動資源管理try-with-resources是Java 7中引入的一種新的異常處理機制,它可以自動關閉try-catch塊中使用的資源。

資源

資源是指程式完成後需要關閉的物件。例如,讀取檔案、資料庫連線等等。

用法

要使用try-with-resources語句,只需在括號內宣告所需的資源,建立的資源將在塊結束時自動關閉。以下是try-with-resources語句的語法。

語法

try(FileReader fr = new FileReader("file path")) {    
   // use the resource    
   } catch () {
      // body of catch    
   }
}

以下程式使用try-with-resources語句讀取檔案中的資料。

示例

import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {

   public static void main(String args[]) {
      try(FileReader fr = new FileReader("E://file.txt")) {
         char [] a = new char[50];
         fr.read(a);   // reads the contentto the array
         for(char c : a)
         System.out.print(c);   // prints the characters one by one
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

舊的資源管理方式

在Java 7之前,當我們使用任何資源(如流、連線等)時,必須使用finally塊顯式關閉它們。在下面的程式中,我們使用FileReader讀取檔案中的資料,並使用finally塊關閉它。

示例

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadData_Demo {

   public static void main(String args[]) {
      FileReader fr = null;        try {
         File file = new File("file.txt");
         fr = new FileReader(file); char [] a = new char[50];
         fr.read(a);   // reads the content to the array
         for(char c : a)
         System.out.print(c);   // prints the characters one by one
      } catch (IOException e) {
         e.printStackTrace();
      }finally {
         try {
            fr.close();
         } catch (IOException ex) {              ex.printStackTrace();
         }
      }
   }
}

要點

使用try-with-resources語句時,請記住以下幾點。

  • 要將類與try-with-resources語句一起使用,它必須實現AutoCloseable介面,並且它的close()方法會在執行時自動呼叫。

  • 可以在try-with-resources語句中宣告多個類。

  • 在try-with-resources語句的try塊中宣告多個類時,這些類將按相反的順序關閉。

  • 除了在括號內宣告資源外,其他一切都與try塊的普通try/catch塊相同。

  • 在try塊中宣告的資源會在try塊開始之前例項化。

  • 在try塊中宣告的資源隱式宣告為final。

更新於:2020年6月18日

701 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.