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

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

问题描述

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

Let's say I have a serializable class AppMessage.

我想通过套接字将它作为 byte[] 传输到另一台机器,在那里它从接收到的字节中重建.

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

我怎样才能做到这一点?

How could I achieve this?

推荐答案

准备要发送的字节数组:

Prepare the byte array to send:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream 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天全站免登陆