1.首先对象要继承Serializable接口
将字节转换为对象
01 |
public static Object 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 |
return obj;
|
16 |
} |
将对像转换为字节
01 |
public static byte [] 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 |
return bytes;
|
18 |
} |