Recently the company has used Message Queuing, and as we know is the binary form between message queues, share the conversion between bytes and objects in Java.
The main use of the Bytearrayoutputstream and objectoutputstream two output streams, as well as Bytearrayinputstream and objectinputstream two input streams. Don't say much nonsense, go directly to the code!
/** * @FileName: Bytetoobject.java * @Package: Com.test * @Description: TODO * @author: LUCKY * @date: 2015 Year December 25 pm 12:18:08 * @version V1.0 */package com.test;import java.io.bytearrayinputstream;import Java.io.ByteArray Outputstream;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.util.HashMap;import java.util.map;/** * @ClassName: Bytetoobject * @Description: Conversion between bytes and objects * @author: LUCKY * @date: December 25, 2015 PM 12:1 8:08 */public class Bytetoobject {public static void main (string[] args) throws Exception {Student stu=new Student (); Stu.setage ("a"); Stu.setname ("Zhang San"); Map<string, string> map=new hashmap<string, string> () map.put ("001", "001"), Map.put ("002", "002"); Stu.setwage (map); Bytearrayoutputstream byt=new Bytearrayoutputstream (); ObjectOutputStream obj=new ObjectOutputStream (byt); o Bj.writeobject (Stu); byte[] Bytes=byt.tobytearray (); System.out.println (bytes); Bytearrayinputstream byteint=new Bytearrayinputstream (bytes); ObjectInputStream objint=new ObjectInputStream (byteint); Student stu2=new Student (); stu2= (Student) objint.readobject (); System.out.println (STU2);}}
Conversion between bytes and objects in Java