假设我有一个可序列化的类AppMessage
我想将它作为byte[]通过套接字传输到另一台机器,在那里它是从接收到的字节重建的
我怎样才能做到这一点
准备要发送的字节数组:
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream out=null;
试一试{
out=新对象输出流(bos);
out.writeObject(您的对象);
out.flush();
byte[]yourBytes=bos.toByteArray();
...
}最后{
试一试{
bos.close();
}捕获(IOEX异常){
//忽略关闭异常
}
}
从字节数组创建对象:
ByteArrayInputStream bis=newbytearrayinputstream(yourBytes);
ObjectInput in=null;
试一试{
in=新的ObjectInputStream(bis);
对象o=in.readObject();
...
}最后{
试一试{
if(in!=null){
in.close();
}
}捕获(IOEX异常){
//忽略关闭异常
}
}