// 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();
0
准备要发送的字节:
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
}
}
7 回答
准备要发送的字节:
从字节创建对象:
最好的方法是使用Apache Commons Lang中的
SerializationUtils
.要序列化:
要反序列化:
如上所述,这需要Commons Lang库 . 它可以使用Gradle导入:
Maven的:
Jar file
还有更多方法提到here
或者,可以导入整个集合 . 参考this link
如果使用Java> = 7,则可以使用try with resources改进已接受的解决方案:
反过来说:
可以通过 SerializationUtils ,通过ApacheUtils的序列化和反序列化方法将对象转换为byte [],反之亦然,如@uris answer中所述 .
通过序列化将对象转换为byte []:
通过反序列化将byte []转换为对象::
点击链接到Download org-apache-commons-lang.jar
单击以集成.jar文件:
FileName - > Open Medule Settings - > Select your module - > Dependencies - > Add Jar file 你完成了 .
Hope this helps .
我还建议使用SerializationUtils工具 . 我想对@Abilash做出错误的评论 .
SerializationUtils.serialize()
方法不限于1024字节,这与此处的另一个答案相反 .乍一看,您可能认为
new ByteArrayOutputStream(1024)
只允许固定大小 . 但是如果你仔细看看ByteArrayOutputStream
,你会发现如果有必要,流会增长:java 8的代码示例: