利用ObjectInputStream跟ObjectOutputStream实现对象的序列化
利用ObjectInputStream和ObjectOutputStream实现对象的序列化
package cn.felay.io; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * 对象的持久化 * @author <a mailto:felayman@163.com>felayman</a> * @timer 2014年6月10日 下午6:37:16 */ public class ObjectInputStreamDemo { public static void main(String[] args) { ObjectInputStream in = null; ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream( "src/res/student.dat")); out.writeObject(new Student(1, "方", "磊")); out.writeObject(new Student(2, "刘", "欢")); out.writeObject(new Student(3, "宗", "阳")); in = new ObjectInputStream(new FileInputStream( "src/res/student.dat")); for (int i = 0; i < 3; i++) { System.out.println(in.readObject().toString()); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } class Student implements Serializable { private static final long serialVersionUID = 5987036960278879461L; private int id; public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } private String firstName; public Student(int id, String firstName, String lastName) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; } private String lastName; @Override public String toString() { return "ID:" + this.id + " " + this.firstName + " " + this.lastName; } }