日期:2014-05-20 浏览次数:20865 次
package cn.java.file; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; public class SE implements Externalizable{ private String name; private Gender gender; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public SE(String name, Gender gender, int age) { super(); this.name = name; this.gender = gender; this.age = age; } public SE() { super(); } //当反序列化对象时,该方法自动调用 @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { System.out.println("反序列化方法执行。"); Date d=(Date)in.readObject(); System.out.println(d); this.setName(in.readObject().toString()); this.setGender((Gender)in.readObject()); this.setAge((int)(in.readObject())); } //当序列化对象时,该方法自动调用 @Override public void writeExternal(ObjectOutput out) throws IOException { System.out.println("序列化方法执行。"); Date d=new Date(); System.out.println(d); out.writeObject(d); out.writeObject(this.getGender()); out.writeObject(this.getName()); out.writeObject(this.getAge()); } @Override public String toString() { return "年龄: " + age + "名字: "+name+"性别: "+gender; } } enum Gender{ Female,Male }
package cn.java.file; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerinalizableSE { /** * 序列化对象到文件 * @param fileName */ public static void serialize(String fileName){ try { ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(fileName)); SE s1,s2,s3; s1=new SE("lori",Gender.Male,27); s2=new SE("winter",Gender.Male,21); s3=new SE("super",Gender.Female,25); out.writeObject(s1); out.writeObject(s2); out.writeObject(s3); out.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 从文件反序列化到对象 * @param fileName */ public static void deserialize(String fileName){ SE []se=new SE[3]; try { ObjectInputStream in=new ObjectInputStream(new FileInputStream(fileName)); se[0]=(SE)(in.readObject()); se[1]=(SE)(in.readObject()); se[2]=(SE)(in.readObject()); for (int i = 0; i < se.length; i++) { System.out.println(se[i].toString()); } in.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { //序列化对象 SerinalizableSE.serialize("D:\\SE.txt"); System.out.println("序列化完毕"); //反序列化对象 SerinalizableSE.deserialize("D:\\SE.txt"); System.out.println("反序列化完毕"); } }