最简化的 序列化保存 java 对象

  1. public class Test1 {
  2.  final static ObjectStreamClass desc = ObjectStreamClass.lookupAny(MyBean.class);
  3.  public static void main(String[] args) throws IOException, ClassNotFoundException {
  4.   
  5.   File f = new File("f://f"+System.currentTimeMillis()+".ser");
  6.   FileOutputStream fos = new FileOutputStream(f);
  7.   java.io.ObjectOutputStream oos = new MyObjectOutputStream(fos);
  8.   oos.writeObject(new MyBean((byte)1));
  9.   oos.writeObject(new MyBean((byte)2));
  10.   oos.flush();
  11.   oos.close();
  12.   
  13.   
  14.   FileInputStream fis = new FileInputStream(f);
  15.   java.io.ObjectInputStream ois = new MyObjectInputStream(fis);
  16.   System.out.println(ois.readObject());
  17.   System.out.println(ois.readObject());
  18.   ois.close();
  19.  }
  20.  static 
  21.  class MyObjectOutputStream extends  ObjectOutputStream{
  22.   public MyObjectOutputStream(OutputStream out) throws IOException {
  23.    super(out);
  24.   }
  25.   
  26.   @Override
  27.   protected void writeStreamHeader() throws IOException{}
  28.   
  29.   @Override
  30.   protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException{}
  31.  }
  32.  static
  33.  class MyObjectInputStream extends ObjectInputStream{
  34.   public MyObjectInputStream(InputStream in) throws IOException {
  35.    super(in);
  36.   }
  37.   
  38.   @Override
  39.   protected void readStreamHeader() throws IOException, StreamCorruptedException{}
  40.   
  41.   @Override
  42.   protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException{
  43.    return desc;
  44.      }
  45.  }
  46. }
  47. class MyBean implements Serializable{
  48.  private static final long serialVersionUID = 0L;
  49.  public MyBean(byte id){
  50.   this.i = id;
  51.  }
  52.  byte i=0;
  53.  @Override
  54.  public String toString(){
  55.   return this.getClass().getName()+":"+i;
  56.  }
  57. }

posted on 2008-12-18 13:35  天之南  阅读(144)  评论(0)    收藏  举报

导航