啥是序列化和反序列化
- 序列化:把对象转为字节序列的过程称为对象的序列化
- 反序列化:把字节序列恢复为对象的过程称为反序列化
- 有时候我们想把一些信息持久化保存起来,那么序列化的意思就是把内存里面的这些对象给变成一连串的字节描述的过程,常见的就是变成文件.
什么时候需要序列化和反序列化
- 把内存中的对象状态保存到一个文件中或者数据库中的时候
- 用套接字在网络上传送对象的时候
将内存中的对象写进文件
class SerializeDemo{
private static class Person implements Serializable{//具备了序列化的能力
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public static void main(String[] args) throws IOException{
Person person = new Person("lee",21);//把这个对象存到文件里头
Person person1 = new Person("jack",55);
OutputStream os = new FileOutputStream("Person对象.bin");
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(person);
oos.writeObject(person1);
}
}
从文件中写出来,反序列化(二进制设备数据还原成内存中的对象)
public static void main(String[] args) throws IOException, ClassNotFoundException {
InputStream is = new FileInputStream("Person对象.bin");
ObjectInputStream ois = new ObjectInputStream(is);
Person p ;
p = (Person)ois.readObject();
System.out.println(p);
p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
序列化 的作用
1.持久化(长期保存)
2.传输(经网络)