最簡化的 序列化儲存 java 對象

來源:互聯網
上載者:User
  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. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.