一、什么是对象序列化和反序列化
序列化就是将对象转换成与运行平台和程序无关的字节序列。序列化的目的是将对象保存在磁盘文件中或者在网络上直接传输对象。
反序列化就是将字节序列还原为对象。
二、对象序列化的步骤
1.创建一个类继承Serializable接口,表明该类的实例是可序列化的,并创建对象
2.将对象转成字节序列写入文件或传到网络
3.从文件或网络读取字节序列还原为对象
三、示例代码
/**
* @author created by jackie on 2020/4/24
* @description:
*/
public class UserInfo2 implements java.io.Serializable //表明该类可以序列化
{
private String userName;
private String city;
public UserInfo2(String userName, String city) {
this.userName = userName;
this.city = city;
}
@Override
public String toString() {
return "UserInfo2{" +
"userName='" + userName + '\'' +
", city='" + city + '\'' +
'}';
}
}
/**
* @author created by jackie on 2020/4/24
* @description:
*/
public class ObjectSerialTest {
public static void main(String[] args) {
try {
//创建输出流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
//创建输入流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));
//写入对象
UserInfo2 user = new UserInfo2("jackie", "GuangZhou");
oos.writeObject(user);
//读取对象
UserInfo2 result = (UserInfo2) ois.readObject();
System.out.println(result);
oos.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}