java7增強的try語句關閉資源


java7增強的try語句關閉資源

傳統的關閉資源方式

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Student implements Serializable {
	private String name;

	public Student(String name) {
		this.name = name;
	}
}

public class test2 {
	public static void main(String[] args) throws Exception {
		Student s = new Student("WJY");
		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();
				}
			}
		}
	}
}
  • 使用finally塊來關閉物理資源,保證關閉操作總是會被執行。
  • 關閉每個資源之前首先保證引用該資源的引用變量不為null。
  • 為每一個物理資源使用單獨的try...catch塊來關閉資源,保證關閉資源時引發的異常不會影響其他資源的關閉。

以上方式導致finally塊代碼十分臃腫,程序的可讀性降低。

java7增強的try語句關閉資源

為了解決以上傳統方式的問題, Java7新增了自動關閉資源的try語句。它允許在try關鍵字后緊跟一對圓括號,里面可以聲明、初始化一個或多個資源,此處的資源指的是那些必須在程序結束時顯示關閉的資源(數據庫連接、網絡連接等),try語句會在該語句結束時自動關閉這些資源。


public class test2 {
	public static void main(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接口


免責聲明!

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



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