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(); } } } } }