java实现序列化的两种方式

2019-11-15 00:00:00 方式 序列化 两种

1.Serializable接口

2.Exteranalizable接口

public class Demo2 implements Externalizable{

    transient private String s="sss";
    public int b=10;
    public String ss="iiii";
    public int a=1;
    
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(ss);
        out.writeObject(a);
    }
    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        ss =(String)in.readObject();
        a =(Integer)in.readObject();
    }
    @Override
    public String toString() {
        return "Demo2 [ss=" + ss + ", a=" + a + "]";
    }
}
测试:

public
class Test { public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { Demo2 demo2=new Demo2(); ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:\\Desktop\\a.txt")); oos.writeObject(demo2); oos.close(); ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:\\Desktop\\a.txt")); Object object = ois.readObject(); System.out.println(object); ois.close(); } }

《java实现序列化的两种方式》

 

 

    原文作者:crazy戴夫
    原文地址: https://www.cnblogs.com/crazy-lc/p/11862798.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章