1.序列化与反序列化的定义:
序列化:把对象转化为字节序列的过程称为对象的序列化。
反序列化:把字节序列恢复为对象的过程称为对象的反序列化。
2.实现序列化(Java对象序列化)
如下代码,我们自己实现一个Person类,在类当中定义成员变量 name , id, email,cloths ,如果要讲Person进行序列化需要实现Serializable接口即可 。
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person(1, "王超", "qq.com");
List<Cloth> list = new ArrayList<>();
list.add(new Cloth("1", "李宁"));
list.add(new Cloth("2", "阿迪"));
person.setCloths(list);
//序列化
ObjectOutputStream objectOutputStream = new ObjectOutputStream
(new FileOutputStream(new File("/Users/yangtongchun/Downloads/yy.txt")));
objectOutputStream.writeObject(person);
//反序列化
ObjectInputStream objectInputStream = new ObjectInputStream
(new FileInputStream(new File("/Users/yangtongchun/Downloads/yy.txt")));
Person copy = (Person) objectInputStream.readObject();
person.getCloths().get(0).setName("100");
System.out.println(person);
System.out.println(copy);
}
}
class Person implements Cloneable, Serializable {
private Integer id;
private String name;
private String email;
private List<Cloth> cloths = new ArrayList<>();
public Person(Integer id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", cloths=" + cloths +
'}';
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void setCloths(List<Cloth> cloths) {
this.cloths = cloths;
}
public List<Cloth> getCloths() {
return cloths;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
}
class Cloth implements Serializable {
private String name;
private String brand;
public Cloth(String name, String brand) {
this.name = name;
this.brand = brand;
}
@Override
public String toString() {
return "Cloth{" +
"name='" + name + '\'' +
", brand='" + brand + '\'' +
'}';
}
public void setName(String name) {
this.name = name;
}
}
相关流的说明:
※ ObjectOutputStream 代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。
※ ObjectInputStream 代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们反序列化为一个对象,并将其返回。