Java--序列化与反序列化

序列化就是把对象变成二进制的过程,可以保存在硬盘中或在网络中传输。

    
/**
 * @author staynight
 */
public class Student implements Serializable {
    /**
     * 序列化uid
     */
    private static final  long serialVersionUID=1L;
    private int age;
    private  String name;
    private transient  String address;//不希望序列化的属性 ,用关键字transient瞬时变量关键字。

    public Student() {
    }

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
       
/**
 * @author staynight
 */
public class SerializableTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student student=new Student();
        student.setAddress("轩尼诗道");
        student.setAge(15);
        student.setName("staynight");
        FileOutputStream fileOutputStream = new FileOutputStream(new File("E:/student"));//文件输出流
        //这里可以换成别的输出流,例如ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //bos.toByteArray();转储字节数组
        ObjectOutputStream oos=new ObjectOutputStream(fileOutputStream);
        oos.writeObject(student);
        oos.flush();
        oos.close();
        //将对象反序列化
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("E:/student")));
        Student student1 =(Student)ois.readObject();

    }
}
posted on 2021-08-11 16:37  15年的夏天  阅读(32)  评论(0)    收藏  举报