序列化反序列化(对象流)

package wtest;

import java.io.Serializable;

public class Person implements Serializable {

/* 反序列化也会自动生成一个suid,并且会和序列化的suid进行相等校验,如果相等,说明序列胡及反序列化是同一个对象,
        则正常执行;如果不相等,...不是同一个对象,则报错.
        如果不想自动生成,只需手动写死就行了    */
    private static final long serialVersionUID = -5453635957058577897L;
    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Person(String name, String age) {
        super();
        this.name = name;
        this.age = age;
    }

    public Person() {
        super();
    }

}


================================================================================================

package wtest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MTest {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        String configFileName = "E:\\conf.properties";
        
        Person per=new Person("zs","21");
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(configFileName));
        oos.writeObject(per); //将对象写入硬盘
        oos.close();

        ObjectInputStream ois=new ObjectInputStream(new FileInputStream(configFileName));
        Object perObj=ois.readObject();
        Person per2=(Person)perObj;
        System.out.println(per2.getName()+","+per2.getAge());
    }
}

猜你喜欢

转载自blog.csdn.net/u013008898/article/details/87554047