最简化的 序列化保存 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. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值