Java7 帶資源的try語句
阿新 • • 發佈:2018-12-14
傳統的關閉資源方式
public class ResourceTryCatch { public static void main(String[] args) throws Exception { Student s = new Student("DEMO"); Student s2 = null; ObjectOutputStream oos = null; ObjectInputStream ois = null; try { //建立物件輸出流 oos = new ObjectOutputStream(new FileOutputStream("b.bin")); //建立物件輸入流 ois = new ObjectInputStream(new FileInputStream("b.bin")); //序列化java物件 oos.writeObject(s); oos.flush(); //反序列化java物件 s2 = (Student) ois.readObject(); } finally { //使用finally塊回收資源 if (oos != null) { try { oos.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (ois != null) { try { ois.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } } class Student implements Serializable { private String name; public Student(String name) { this.name = name; } }
使用finally塊來關閉物理資源,保證關閉操作總是會被執行。
關閉每個資源之前首先保證引用該資源的引用變數不為null。
為每一個物理資源使用單獨的try…catch塊來關閉資源,保證關閉資源時引發的異常不會影響其他資源的關閉。
以上方式導致finally塊程式碼十分臃腫,程式的可讀性降低。
java7增強的try語句關閉資源
為了解決以上傳統方式的問題, Java7新增了自動關閉資源的try語句。它允許在try關鍵字後緊跟一對圓括號,裡面可以宣告、初始化一個或多個資源,此處的資源指的是那些必須在程式結束時顯示關閉的資源(資料庫連線、網路連線等),try語句會在該語句結束時自動關閉這些資源。
public static void main2(String[] args) throws Exception { Student s = new Student("WJY"); Student s2 = null; try (//建立物件輸出流 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.bin")); //建立物件輸入流 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.bin")); ) { //序列化java物件 oos.writeObject(s); oos.flush(); //反序列化java物件 s2 = (Student) ois.readObject(); } }
自動關閉資源的try語句相當於包含了隱式的finally塊(用於關閉資源),因此這個try語句可以既沒有catch塊,也沒有finally塊。
被自動關閉的資源必須實現Closeable或AutoCloseable介面。(Closeable是AutoCloseable的子介面,Closeeable接口裡的close()方法宣告丟擲了IOException,;AutoCloseable接口裡的close()方法宣告丟擲了Exception)
被關閉的資源必須放在try語句後的圓括號中宣告、初始化。如果程式有需要自動關閉資源的try語句後可以帶多個catch塊和一個finally塊。
Java7幾乎把所有的“資源類”(包括檔案IO的各種類,JDBC程式設計的Connection、Statement等介面……)進行了改寫,改寫後的資源類都實現了AutoCloseable或Closeable介面。