Java对象序列化和反序列化

时间:2023-02-17 13:57:18

看了:http://blog.csdn.net/liang__/article/details/5726155,然后自己写了个试下


Student student = new Student();
student.setId(11l);
student.setName("test11");
System.out.println(student);
/* 结果
* id:=11, name:=test11
*/

//序列化
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(student);
oos.flush();
oos.close();
bos.close();
String ser = new BASE64Encoder().encode(bos.toByteArray());
System.out.println(ser);
/*结果
rO0ABXNyAB5jb20ubG1pa3kuc3R1ZGVudC5wb2pvLlN0dWRlbnRA6agITr3FRQIAAUwABG5hbWV0
ABJMamF2YS9sYW5nL1N0cmluZzt4cgAgY29tLmxtaWt5LmRhdGFiYXNlLnBvam8uQmFzZVBvam+3
fX/mtiV9YQIAAUoAAmlkeHAAAAAAAAAAC3QABnRlc3QxMQ==
*/

//反序列化
ByteArrayInputStream bis = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(ser));
ObjectInputStream ois = new ObjectInputStream(bis);
Student serStudent = (Student)ois.readObject();
bis.close();
ois.close();
System.out.println(serStudent);
/* 结果
* id:=11, name:=test11
*/