Java中字節與對象之間的轉換
阿新 • • 發佈:2017-07-13
ring str arr cti void too trac port ear
近期公司裏面用到了消息隊列,而正如我們知道的是消息隊列之間的是通過二進制形式的。以下就分享一下java中字節與對象之間的轉換。
主要是用到了ByteArrayOutputStream和ObjectOutputStream兩個輸出流,以及ByteArrayInputStream和ObjectInputStream兩個輸入流。
廢話不多說了,直接上代碼吧!
/** * @FileName: ByteToObject.java * @Package:com.test * @Description: TODO * @author: LUCKY * @date:2015年12月25日 下午12:18:08 * @version V1.0 */ package com.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; /** * @ClassName: ByteToObject * @Description: 字節與對象之間的轉換 * @author: LUCKY * @date:2015年12月25日 下午12:18:08 */ public class ByteToObject { public static void main(String[] args) throws Exception { Student stu=new Student(); stu.setAge("15"); stu.setName("張三"); 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); obj.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); } }
Java中字節與對象之間的轉換