java中对象与字节数组相互转换

时间:2023-01-11 10:21:24

1.首先对象要继承Serializable接口

将字节转换为对象

01 public staticObject ByteToObject(byte[] bytes) {
02 Object obj = null;
03 try {
04     // bytearray to object
05     ByteArrayInputStream bi =new ByteArrayInputStream(bytes);
06     ObjectInputStream oi =new ObjectInputStream(bi);
07  
08     obj = oi.readObject();
09     bi.close();
10     oi.close();
11 } catch(Exception e) {
12     System.out.println("translation"+ e.getMessage());
13     e.printStackTrace();
14 }
15     returnobj;
16 }

将对像转换为字节

view sourceprint?
01 public staticbyte[] ObjectToByte(java.lang.Object obj) {
02     byte[] bytes =null;
03     try{
04         // object to bytearray
05         ByteArrayOutputStream bo =new ByteArrayOutputStream();
06         ObjectOutputStream oo =new ObjectOutputStream(bo);
07         oo.writeObject(obj);
08  
09         bytes = bo.toByteArray();
10  
11         bo.close();
12         oo.close();
13     } catch (Exception e) {
14         System.out.println("translation"+ e.getMessage());
15         e.printStackTrace();
16     }
17     returnbytes;
18 }