下图中,Java对象被转换成字节流,然后存储在各种形式的存储中,这个过程叫做序列化。图右侧,内存中的字节流转换成Java对象,这个过程叫作反序列化。

public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private String serializeValueName;
    private transient int nonSerializeValueSalary;
    public String getSerializeValueName() {
        return serializeValueName;
    }
    public void setSerializeValueName(String serializeValueName) {
        this.serializeValueName = serializeValueName;
    }
    public int getNonSerializeValueSalary() {
        return nonSerializeValueSalary;
    }
    public void setNonSerializeValueSalary(int nonSerializeValueSalary) {
        this.nonSerializeValueSalary = nonSerializeValueSalary;
    }
    @Override
    public String toString() {
        return "Employee \[serializeValueName=" + serializeValueName + "\]";
    }
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializingObject {
    public static void main(String\[\] args) {
        Employee employeeOutput = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        employeeOutput = new Employee();
        employeeOutput.setSerializeValueName("Aman");
        employeeOutput.setNonSerializeValueSalary(50000);
        try {
            fos = new FileOutputStream("Employee.ser");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(employeeOutput);
        System.out.println("Serialized data is saved in Employee.ser file");
        oos.close();
        fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}