Java可序列化对象到字节数组
假设我有一个可序列化的类AppMessage 。 
 我想将它作为byte[]通过套接字传输到另一台机器,从接收的字节中重build它。 
我怎么能做到这一点?
准备发送的字节:
 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 } } 
从字节创build对象:
 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 } } 
 最好的方法是使用Apache Commons Lang的 SerializationUtils 。 
序列化:
 byte[] data = SerializationUtils.serialize(yourObject); 
反序列化:
 YourObject yourObject = SerializationUtils.deserialize(data) 
如前所述,这需要Commons Lang库。 它可以使用Gradle导入:
 compile 'org.apache.commons:commons-lang3:3.5' 
Maven的:
 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> 
Jar文件
在这里提到更多的方法
或者,整个集合可以导入。 参考这个链接
如果使用Java> = 7,则可以使用资源尝试来改进可接受的解决scheme:
 private byte[] convertToBytes(Object object) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(object); return bos.toByteArray(); } } 
反过来说:
 private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException { try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { return in.readObject(); } } 
可以通过SerializationUtils完成,通过由ApacheUtils的serialize&deserialize方法将对象转换为byte [],反之亦然,如@uris回答中所述。
通过序列化将对象转换为byte []:
 byte[] data = SerializationUtils.serialize(object); 
通过反序列化将byte []转换为对象
 Object object = (Object) SerializationUtils.deserialize(byte[] data) 
点击链接下载org-apache-commons-lang.jar
通过单击来集成.jar文件:
文件名 – > 打开Medule设置 – > select你的模块 – > 依赖项 – > 添加jar文件 ,你就完成了。
希望这有助于 。