码迷,mamicode.com
首页 > 其他好文 > 详细

任意类型和二进制互转工具类

时间:2020-02-20 17:18:03      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:bytearray   new   puts   pre   exception   null   对象   cto   put   

 1 public class SerializeUtil {
 2     /**
 3      * 任意类型和二进制互转
 4      * @param obj
 5      * @return
 6      */
 7     public static byte [] serialize(Object obj){
 8         ObjectOutputStream obi=null;
 9         ByteArrayOutputStream bai=null;
10         try {
11             bai=new ByteArrayOutputStream();
12             obi=new ObjectOutputStream(bai);
13             obi.writeObject(obj);
14             byte[] byt=bai.toByteArray();
15             return byt;
16         } catch (IOException e) {
17             e.printStackTrace();
18         }
19         return null;
20     }
21 
22     /**
23      * 把二进制反序列化为对象
24      * @param byt
25      * @return
26      */
27     public static Object unserizlize(byte[] byt){
28         ObjectInputStream oii=null;
29         ByteArrayInputStream bis=null;
30         bis=new ByteArrayInputStream(byt);
31         try {
32             oii=new ObjectInputStream(bis);
33             Object obj=oii.readObject();
34             return obj;
35         } catch (Exception e) {
36 
37             e.printStackTrace();
38         }
39 
40 
41         return null;
42     }
43 }

注意:实体类二进制转化必须序列化

任意类型和二进制互转工具类

标签:bytearray   new   puts   pre   exception   null   对象   cto   put   

原文地址:https://www.cnblogs.com/xieshilin/p/12336150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!