将Object对象转换成byte[]
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;
}
本文提供了两个实用的方法:一是将Java中的任意对象转换为字节数组,二是将字节数组还原为原始的对象。这两种转换利用了Java的序列化机制,通过ByteArrayOutputStream和ObjectOutputStream实现对象到字节数组的转换;通过ByteArrayInputStream和ObjectInputStream完成字节数组到对象的还原。
1462

被折叠的 条评论
为什么被折叠?



