Java 可序列化对象到字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2836646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Serializable Object to Byte Array
提问by iTEgg
Let's say I have a serializable class AppMessage
.
假设我有一个可序列化的类AppMessage
。
I would like to transmit it as byte[]
over sockets to another machine where it is rebuilt from the bytes received.
我想byte[]
通过套接字将它传输到另一台机器,在那里它从收到的字节中重建。
How could I achieve this?
我怎么能做到这一点?
采纳答案by Taylor Leese
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
}
}
Create an object from a byte array:
从字节数组创建一个对象:
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
}
}
回答by uris
The best way to do it is to use SerializationUtils
from Apache Commons Lang.
最好的方法是SerializationUtils
从 Apache Commons Lang 使用。
To serialize:
序列化:
byte[] data = SerializationUtils.serialize(yourObject);
To deserialize:
反序列化:
YourObject yourObject = SerializationUtils.deserialize(data)
As mentioned, this requires Commons Lang library. It can be imported using Gradle:
如前所述,这需要 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>
And more ways mentioned here
以及这里提到的更多方式
Alternatively, the whole collection can be imported. Refer this link
或者,可以导入整个集合。参考这个链接
回答by Víctor Romero
If you use Java >= 7, you could improve the accepted solution using try with resources:
如果您使用 Java >= 7,则可以使用try with resources改进已接受的解决方案:
private byte[] convertToBytes(Object object) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(object);
return bos.toByteArray();
}
}
And the other way around:
反过来说:
private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInput in = new ObjectInputStream(bis)) {
return in.readObject();
}
}
回答by Pankaj Lilan
Can be done by SerializationUtils, by serialize & deserialize method by ApacheUtils to convert object to byte[] and vice-versa , as stated in @uris answer.
可以通过SerializationUtils完成,通过 ApacheUtils 的序列化和反序列化方法将对象转换为 byte[] ,反之亦然,如@uris 回答中所述。
To convert an object to byte[] by serializing:
通过序列化将对象转换为 byte[]:
byte[] data = SerializationUtils.serialize(object);
To convert byte[] to object by deserializing::
通过反序列化将 byte[] 转换为对象:
Object object = (Object) SerializationUtils.deserialize(byte[] data)
Click on the link to Download org-apache-commons-lang.jar
点击链接下载 org-apache-commons-lang.jar
Integrate .jar file by clicking:
通过单击集成 .jar 文件:
FileName-> Open Medule Settings-> Select your module-> Dependencies-> Add Jar fileand you are done.
文件名->打开 Medule 设置->选择你的模块->依赖项->添加 Jar 文件,你就完成了。
Hope this helps.
希望这会有所帮助。
回答by gzg_55
I also recommend to use SerializationUtils tool. I want to make a ajust on a wrong comment by @Abilash. The SerializationUtils.serialize()
method is notrestricted to 1024 bytes, contrary to another answer here.
我还建议使用 SerializationUtils 工具。我想对@Abilash 的错误评论进行调整。该SerializationUtils.serialize()
方法不局限于1024个字节,违背了这里的另一个答案。
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
}
return baos.toByteArray();
}
At first sight, you may think that new ByteArrayOutputStream(1024)
will only allow a fixed size. But if you take a close look at the ByteArrayOutputStream
, you will figure out the the stream will grow if necessary:
乍一看,您可能会认为new ByteArrayOutputStream(1024)
只允许固定大小。但是,如果您仔细查看ByteArrayOutputStream
,您会发现如果有必要,流会增长:
This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using
toByteArray()
andtoString()
.
这个类实现了一个输出流,其中数据被写入一个字节数组。缓冲区会随着数据写入而自动增长。可以使用
toByteArray()
和 检索数据toString()
。
回答by user207421
I would like to transmit it as byte[] over sockets to another machine
我想通过套接字将它作为字节 [] 传输到另一台机器
// When you connect
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// When you want to send it
oos.writeObject(appMessage);
where it is rebuilt from the bytes received.
它是从接收到的字节重建的。
// When you connect
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// When you want to receive it
AppMessage appMessage = (AppMessage)ois.readObject();
回答by Mohamed.Abdo
code example with java 8+:
java 8+的代码示例:
public class Person implements Serializable {
private String lastName;
private String firstName;
public Person() {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "firstName: " + firstName + ", lastName: " + lastName;
}
}
public interface PersonMarshaller {
default Person fromStream(InputStream inputStream) {
try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
Person person= (Person) objectInputStream.readObject();
return person;
} catch (IOException | ClassNotFoundException e) {
System.err.println(e.getMessage());
return null;
}
}
default OutputStream toStream(Person person) {
try (OutputStream outputStream = new ByteArrayOutputStream()) {
ObjectOutput objectOutput = new ObjectOutputStream(outputStream);
objectOutput.writeObject(person);
objectOutput.flush();
return outputStream;
} catch (IOException e) {
System.err.println(e.getMessage());
return null;
}
}
}
回答by Asad Shakeel
Another interesting method is from com.fasterxml.Hymanson.databind.ObjectMapper
另一个有趣的方法是从 com.fasterxml.Hymanson.databind.ObjectMapper
byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)
byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)
Maven Dependency
Maven 依赖
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
</dependency>
回答by xxg
Spring Framework org.springframework.util.SerializationUtils
弹簧框架 org.springframework.util.SerializationUtils
byte[] data = SerializationUtils.serialize(obj);
回答by Supun Wijerathne
If you are using spring, there's a util class available in spring-core. You can simply do
如果您使用的是 spring,则 spring-core 中有一个 util 类可用。你可以简单地做
import org.springframework.util.SerializationUtils;
byte[] bytes = SerializationUtils.serialize(anyObject);
Object object = SerializationUtils.deserialize(bytes);