// byte array to Object
public void byteArr2Object(byte[] buf) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (buf);
ObjectInputStream
ois = new ObjectInputStream (bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}
// object to byte array
public void objectToByteArr(Object o) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.flush();
bytes = bos.toByteArray ();
oos.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
}
【Java】对象、字节转换
最新推荐文章于 2023-02-24 12:12:19 发布
本文介绍如何将Java中的对象转换为字节数组,以及如何从字节数组还原对象。这两种方法使用了Java的序列化和反序列化机制,通过ObjectInputStream和ObjectOutputStream实现。
776

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



