java7增強(qiáng)的try語句關(guān)閉資源
傳統(tǒng)的關(guān)閉資源方式
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 { //創(chuàng)建對象輸出流 oos = new ObjectOutputStream(new FileOutputStream("b.bin")); //創(chuàng)建對象輸入流 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(); } } } } }