java序列化

public class TestJavaSerialization {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person zhansan = new Person();
zhansan.setAddress("hangzhou");
zhansan.setAge(30);
zhansan.setBirth(new Date());
zhansan.setName("zhansan");

//定义一个字节数组输出流
ByteArrayOutputStream os = new ByteArrayOutputStream();
//对象输出流
ObjectOutputStream out = new ObjectOutputStream(os);
//将对象写入到字节数组输出,进行序列化
out.writeObject(zhansan);
byte[] zhansanByte = os.toByteArray();

//字节数组输入流
ByteArrayInputStream is = new ByteArrayInputStream(zhansanByte);
//执行反序列化,从流中读取对象
ObjectInputStream in = new ObjectInputStream(is);
Person person = (Person)in.readObject();

System.out.println("name : " + person.getName() + ", age : " + person.getAge());
}
}
posted @ 2020-11-27 21:04  伤心的鸽子  阅读(95)  评论(0编辑  收藏  举报