byte[]とObject間の相互転送
1230 ワード
Objectオブジェクトをbyte[]に変換する
byte[]をObjectに変換
public static byte[] getBytes(Object obj) {
try {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bs);
oos.writeObject(obj);
byte[] buf = bs.toByteArray();
oos.flush();
return buf;
}
catch (IOException e) {
e.printStackTrace();
LOGGER.info("convert to byte fail");
}
return null;
}
byte[]をObjectに変換
public static Object getObject(byte[] bs) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bs);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
catch (IOException e) {
LOGGER.info("convert to Object fail");
}
catch (ClassNotFoundException e) {
LOGGER.info("File not found");
}
return null;
}