首页 文章

Java可序列化对象到字节数组

提问于
浏览
257

假设我有一个可序列化的类 AppMessage .

我想将它作为 byte[] 通过套接字传输到另一台机器,在那里它从接收到的字节重建 .

我怎么能实现这个目标?

7 回答

  • 3

    我想通过套接字将其作为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();
    
  • 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
      }
    }
    
  • 274

    最好的方法是使用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 file

    还有更多方法提到here

    或者,可以导入整个集合 . 参考this link

  • 381

    如果使用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();
        } 
    }
    

    反过来说:

    private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInput in = new ObjectInputStream(bis)) {
            return in.readObject();
        } 
    }
    
  • 1

    可以通过 SerializationUtils ,通过ApacheUtils的序列化和反序列化方法将对象转换为byte [],反之亦然,如@uris answer中所述 .

    通过序列化将对象转换为byte []:

    byte[] data = SerializationUtils.serialize(object);
    

    通过反序列化将byte []转换为对象::

    Object object = (Object) SerializationUtils.deserialize(byte[] data)
    

    点击链接到Download org-apache-commons-lang.jar

    单击以集成.jar文件:

    FileName - > Open Medule Settings - > Select your module - > Dependencies - > Add Jar file 你完成了 .

    Hope this helps .

  • 1

    我还建议使用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()来检索数据 .

  • 75

    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;
        }
    
    }
    
    }
    

相关问题