package externalizable.cn; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; public class ExternalizableDemo { public static void main(String[] args) throws Throwable { ser(); dser(); } //序例化类 public static void ser() throws Throwable{ File f = new File("d:"+File.separator+"e.txt"); OutputStream out = new FileOutputStream(f); ObjectOutputStream otp = new ObjectOutputStream(out); //void writeObject(Object obj) 将指定的对象写入 ObjectOutputStream。 otp.writeObject(new Person("张三",30)); otp.close(); } //反序例化类 public static void dser() throws Throwable{ File f = new File("d:"+File.separator+"e.txt"); InputStream ip = new FileInputStream(f); //new 一个对象输入流 ObjectInputStream oji = new ObjectInputStream(ip); Object object = oji.readObject(); oji.close(); System.out.println(object); } }
package externalizable.cn; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /* * 接口 Externalizable 用户自己指定序例化的内容 * public interface Externalizable extends Serializable{ * public void readExternal(ObjectInput in); * public void writeExternal(ObjectOutput out); * } */ public class Person implements Externalizable { private String name; private int age; //无参构造:要实现 Externalizable 接口,必须得有一个无参构造 public Person(){} public Person(String name,int age){ this.age = age; this.name = name; } public String toString (){ return "姓名:"+this.name+",年龄:"+this.age; } //实现两个抽象方法 public void readExternal(ObjectInput in) throws IOException{ try { this.name = (String)in.readObject(); this.age = (int)in.readInt(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void writeExternal(ObjectOutput out) throws IOException{ out.writeObject(this.name); out.writeInt(this.age); } }