java的序列化与返序列化

  数据若需要再网络上传输,必须被转化为二进制流,在java中将对象转化为二进制流的过程被称为序列化,反之将二进制流恢复为对象的过程称为返序列化。数据序列化的成熟方案有很多,将介绍两种比较流行的方案。

  一,java的内置的序列化方式不需要引入第三方的包,使用简单在对效率不高的场景也是一个很好的选择,只需要使用java.io下的ObjectOutPutStream下的writerObject()方法将类的实列序列化为数组,然后通过ObjectInputStream的readerObject()方法将字节数组返序列化为对象。核心代码:

  定义使用字节输出流

  ByteArrayOutputStream bos = new ByteArrayOutputStream();

  定义对象输出流

  ObjectOutPutStream oos = new ObjectOutputStream(bos);

  将对象写入到字节数组输出,进行序列化

  oos.writerObject(person)

  Byte[] personByte = bos.toByteArray()

  字节数组输入流

  ByteArrayInputStream bis = new ByteArrayInputStream(personByte);

  对象输入流

  ObjectInputStream ois = new ObjectInputStream(bis)

  读取返序列化

  Person person = ois.readerObject().toString();

 二java基于Hessian的方式

  需要引入第三方的包hessian-4.0.7.jar,效率较java内置的方式高很多。需要使用com.cauchohessian.io下的HessianOutput下的writerObject()方法将类的实列序列化为数组,然后通过HessianInput的readerObject()方法将字节数组返序列化为对象。核心代码:

  

定义使用字节输出流

  ByteArrayOutputStream bos = new ByteArrayOutputStream();

  定义对象输出流

  HessianOutput hos = new HessianOutput(bos);

  将对象写入到字节数组输出,进行序列化

  hos.writerObject(person)

  Byte[] personByte = bos.toByteArray()

  字节数组输入流

  ByteArrayInputStream bis = new ByteArrayInputStream(personByte);

  对象输入流

  HessianInput his = new HessianInput(personByte)

  读取返序列化

  Person person = ois.readerObject().toString();

  

  

posted @ 2017-10-27 15:20  Derleser  阅读(94)  评论(0)    收藏  举报