假设我有一个可序列化的类AppMessage
。
我想byte[]
通过套接字将其传输到另一台计算机,从接收的字节重建该计算机。
我怎样才能做到这一点?
假设我有一个可序列化的类AppMessage
。
我想byte[]
通过套接字将其传输到另一台计算机,从接收的字节重建该计算机。
我怎样才能做到这一点?
new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)
Answers:
准备要发送的字节数组:
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
}
}
ObjectInput
,ObjectOuput
,ByteArrayOutputStream
并且ByteArrayInputStream
都实现了AutoCloseable
接口,岂不是很好的做法,用它来避免遗漏错误关闭它们?(我不确定这是否是最佳实践,这就是我想知道的原因。)示例:try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)){ /*Do stuff*/ }catch(IOException e){/*suppress exception*/}
。它还消除了对该final
子句及其附加内容的需要try-catch
。
最好的方法是SerializationUtils
从Apache Commons Lang中使用。
序列化:
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>
这里提到的更多方法
或者,可以导入整个集合。引用此链接
SerializationUtils.serialize(o)
,您的对象需要这个implements Serializable
如果您使用Java> = 7,则可以通过尝试使用资源来改善可接受的解决方案:
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的序列化和反序列化方法将对象转换为byte [],反之亦然,如@uris回答中所述。
通过序列化将对象转换为byte []:
byte[] data = SerializationUtils.serialize(object);
通过反序列化将byte []转换为对象:
Object object = (Object) SerializationUtils.deserialize(byte[] data)
单击链接下载org-apache-commons-lang.jar
通过单击以下命令来集成.jar文件:
FileName- > Open Medule Settings- >选择您的模块-> Dependencies- > Add Jar文件,您完成了。
希望这会有所帮助。
我还建议使用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();
}
乍一看,您可能会认为这new ByteArrayOutputStream(1024)
只会允许固定大小。但是,如果您仔细查看ByteArrayOutputStream
,则会发现流在必要时会增长:
此类实现输出流,在该流中,数据被写入字节数组。缓冲区随着数据写入而自动增长。可以使用
toByteArray()
和 检索数据toString()
。
另一个有趣的方法是 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>
如果您正在使用spring,spring-core中有一个util类。你可以做
import org.springframework.util.SerializationUtils;
byte[] bytes = SerializationUtils.serialize(anyObject);
Object object = SerializationUtils.deserialize(bytes);
我想通过套接字将其作为byte []传输到另一台机器
// 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();
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;
}
}
}
如果您想要一个不错的无依赖项复制粘贴解决方案。抓取下面的代码。
MyObject myObject = ...
byte[] bytes = SerializeUtils.serialize(myObject);
myObject = SerializeUtils.deserialize(bytes);
import java.io.*;
public class SerializeUtils {
public static byte[] serialize(Serializable value) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try(ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
outputStream.writeObject(value);
}
return out.toByteArray();
}
public static <T extends Serializable> T deserialize(byte[] data) throws IOException, ClassNotFoundException {
try(ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
//noinspection unchecked
return (T) new ObjectInputStream(bis).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 {
}
}
byte[]
?为什么不直接使用来直接将其写入套接字ObjectOutputStream
并使用来进行读取呢ObjectInputStream
?