Java序列化和反序列化實體為byte[]型別
阿新 • • 發佈:2019-02-13
1、序列化
//序列化為byte[]
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(object);
byte[] b = bos.toByteArray();
return b;
} catch (IOException e) {
System.out.println("序列化失敗 Exception:" + e.toString());
return null;
} finally {
try {
if (oos != null) {
oos.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException ex) {
System.out.println("io could not close:" + ex.toString());
}
}
}
2、反序列化
//反序列化為Object
public static Object deserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("bytes Could not deserialize:" + e.toString());
return null;
} finally {
try {
if (bais != null) {
bais.close();
}
} catch (IOException ex) {
System.out.println("LogManage Could not serialize:" + ex.toString());
}
}
}