Java-对象序列化

对象序列化:在内存中保存的对象数据(包含属性,可用transient关键字阻止某个属性被序列化),进行二进制数据传输的一种操作。前提是对象所在的类要实现java.io.Serializable接口,与Cloneable一样表示一种能力。

package com.joeaaa.file;
/*
* 实现类的序列化
* 序列化:��srcom.joeaaa.file.Person...
* 反序列化:Person{name='Alex', age=20}
 */

import java.io.*;

class Person implements Serializable {
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class SerializableTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 序列化对象
        Person person = new Person("Alex", 20);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/Users/joe/IdeaProjects/java/demo1/src/com/joeaaa/1.ser")));
        oos.writeObject(person); //输出对象
        oos.close();

        //反序列化对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                new File("/Users/joe/IdeaProjects/java/demo1/src/com/joeaaa/1.ser")));
        Person person1 = (Person) ois.readObject(); // 接受对象
        ois.close();
        System.out.println(person1);
    }
}