假设我有一个可序列化的类AppMessage。
我想通过套接字将它作为字节[]传输到另一台机器,在那里它从接收到的字节重建。
我怎么才能做到呢?
假设我有一个可序列化的类AppMessage。
我想通过套接字将它作为字节[]传输到另一台机器,在那里它从接收到的字节重建。
我怎么才能做到呢?
当前回答
我想通过套接字将它作为字节[]传输到另一台机器
// When you connect
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// When you want to send it
oos.writeObject(appMessage);
从接收到的字节重新构建。
// When you connect
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// When you want to receive it
AppMessage appMessage = (AppMessage)ois.readObject();
其他回答
这只是一个被接受的答案的优化代码形式,以防有人想在生产中使用它:
public static void byteArrayOps() throws IOException, ClassNotFoundException{
String str="123";
byte[] yourBytes = null;
// Convert to byte[]
try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);) {
out.writeObject(str);
out.flush();
yourBytes = bos.toByteArray();
} finally {
}
// convert back to Object
try(ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = new ObjectInputStream(bis);) {
Object o = in.readObject();
} finally {
}
}
准备要发送的字节数组:
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
}
}
另一个有趣的方法来自com.fasterxml.jackson.databind.ObjectMapper
byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)
Maven的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
可以通过SerializationUtils完成,通过ApacheUtils的serialize & deserialize方法将对象转换为字节[],反之亦然,如@uris answer中所述。
通过序列化将一个对象转换为字节[]:
byte[] data = SerializationUtils.serialize(object);
通过反序列化将byte[]转换为object::
Object object = (Object) SerializationUtils.deserialize(byte[] data)
点击下载org-apache-commons-lang.jar的链接
通过点击整合.jar文件:
FileName ->打开Medule Settings ->选择你的模块-> Dependencies ->添加Jar文件,完成。
希望这能有所帮助。
我想通过套接字将它作为字节[]传输到另一台机器
// When you connect
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// When you want to send it
oos.writeObject(appMessage);
从接收到的字节重新构建。
// When you connect
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// When you want to receive it
AppMessage appMessage = (AppMessage)ois.readObject();