Java可序列化对象到字节数组
假设我有一个可序列化的类byte[]。
我想通过套接字将其作为byte[]传输到另一台机器,在那里从接收的字节重建它。
我怎么能实现这个目标?
6个解决方案
368 votes
准备要发送的字节:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
out.flush();
byte[] yourBytes = bos.toByteArray();
...
} finally {
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
从字节创建对象:
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
in = new ObjectInputStream(bis);
Object o = in.readObject();
...
} finally {
<