Java可序列化对象到字节数组 [英] Java Serializable Object to Byte Array

查看:1029
本文介绍了Java可序列化对象到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个可序列化的类 AppMessage

Let's say I have a serializable class AppMessage.

我想将其作为<$ c传输$ c> byte [] 通过套接字到另一台机器,从接收的字节重建它。

I would like to transmit it as byte[] over sockets to another machine where it is rebuilt from the bytes received.

我怎么能实现这个?

推荐答案

准备要发送的字节:

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 {
  try {
    if (in != null) {
      in.close();
    }
  } catch (IOException ex) {
    // ignore close exception
  }
}

这篇关于Java可序列化对象到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆