java achieve two ways serialized

1.Serializable Interface

2.Exteranalizable Interface

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(); } }

 

 

Guess you like

Origin www.cnblogs.com/crazy-lc/p/11862798.html