首先继承Serializable接口
1.对象转换为字节数组
public byte[] ObjectToByte(java.lang.Object obj) {
byte[] bytes;
try {
//object to bytearray
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
}
catch(Exception e) {
System.out.println("translation"+e.getMessage());
e.printStackTrace();
}
return(bytes);
}
2.字节数组转换为对象
private static java.lang.Object ByteToObject(byte[] bytes) {
java.lang.Object obj;
try {
//bytearray to object
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
obj = oi.readObject();
bi.close();
oi.close();
}
catch(Exception e) {
System.out.println("translation"+e.getMessage());
e.printStackTrace();
}
return obj;
}