java的序列化之Externalizable接口

控制序列化字段还可以使用Externalizable接口替代Serializable借口。此时需要定义一个默认构造器,否则将为得到一个异常(java.io.InvalidClassException: Person; Person; no

valid constructor);还需要定义两个方法(writeExternal()和readExternal())来控制要序列化的字段。

在Person类中

package com.kc.iotest02;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Person implements Externalizable {

    private String name;
    private int age;
    /**
     * 必须有无参数的构造器
     */
    public Person() {
    System.out.println("无参数的构造器");
    }
    public Person(String name,int age) {
        System.out.println("带参数的构造器");
        this.name=name;
        this.age=age;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "姓名是"+name+"年龄是"+age;
    }
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        // TODO Auto-generated method stub

        out.writeObject(name);
        out.writeObject(age);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        // TODO Auto-generated method stub
        this.name=(String)in.readObject();
        this.age=(int)in.readObject();
    }

}

测试类中代码

public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        FileOutputStream fos=null;
        ObjectOutputStream oos=null;
        FileInputStream fis=null;
        ObjectInputStream ois=null;
        try {
            fos=new FileOutputStream(new File("E://javanewlskd.txt"));
            oos=new ObjectOutputStream(fos);
            oos.writeObject(new Person("孙悟空",600));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(oos!=null) {
                oos.close();
            }
        }
        
        try {
            fis=new FileInputStream(new File("E://javanewlskd.txt"));
            ois=new ObjectInputStream(fis);
            Person per=(Person)ois.readObject();
            System.out.println(per);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(ois!=null) {
                ois.close();
            }
        }
        
        
        
    }