309

Let's say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuilt from the bytes received.

How could I achieve this?

lambda
  • 3,075
  • 1
  • 24
  • 31
iTEgg
  • 7,764
  • 19
  • 70
  • 107

12 Answers12

430

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
  }
}
Decoded
  • 808
  • 10
  • 15
Taylor Leese
  • 46,410
  • 27
  • 106
  • 138
  • 53
    That's not how I read the question. To me it sounds like his problem is how to convert the object to a byte[] -- not how to send it. – Taylor Leese May 14 '10 at 18:37
  • 1
    Taylor: yes you got it right. i want to turn the object into a byte[] and transmit it. can you please also provide the code regarding how to turn this byte[] into an object please? – iTEgg May 14 '10 at 18:39
  • Please close always any stream to release the system resources. (Edited in code) – LuckyMalaka Aug 19 '11 at 13:43
  • can this work with objects that I can't implement serializable? – KJW Oct 19 '11 at 11:40
  • how do you deal with the uncaught exceptions on the statements in the "finally" block? – Sam Apr 30 '13 at 11:44
  • thank you so much. this works great sending a custom Settings object (with loads of settings) from android phone to android watch as a byte[] – tom May 26 '16 at 21:39
  • The original closed out but it was edited away. See http://stackoverflow.com/posts/2836659/revisions. – Taylor Leese Mar 17 '17 at 17:46
  • 2
    `ObjectInput`, `ObjectOuput`, `ByteArrayOutputStream` and `ByteArrayInputStream` all implement the `AutoCloseable` interface, wouldn't it be good practice to use it to avoid missing closing them by mistake? (I'm not entirely sure if this is the best practice, that's why I'm wondering.) Example: `try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)){ /*Do stuff*/ }catch(IOException e){/*suppress exception*/}`. It also removes the need for the `final` clause and its additional `try-catch`. – Ludvig Rydahl May 05 '17 at 14:38
  • @LudvigRydahl: answer comes from 2010, Java7 (and try-with-resource) comes from 2011. Otherwise yes, try-with-resource is a good practice - however, that does not apply to the "suppress" part, which is a bad practice. – tevemadar Jun 09 '17 at 23:16
  • @tevemadar that is true about Java 7.however I only posted suppress,which in most cases is a terrible handling, since the answer said ignore. – Ludvig Rydahl Jun 09 '17 at 23:20
  • @LudvigRydahl: Note that the answer ignores exception from resource.close() only. Using try-with-resource, you just close the block and you have the same thing as in the answer (there is no catch in it either, only the finally) – tevemadar Jun 09 '17 at 23:48
  • @Esko There is nothing in the question about RMI or obect construction and deconstruction whatsoever, and this answer covers both serialization and serialization mechanisms. – user207421 Mar 30 '20 at 04:38
324

The best way to do it is to use SerializationUtils from 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:

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

And more ways mentioned here

Alternatively, the whole collection can be imported. Refer this link

The Student Soul
  • 1,612
  • 2
  • 12
  • 11
uris
  • 5,563
  • 2
  • 23
  • 24
  • 58
    Added overhead? Might as well rebuild the wheel at this point. Seriously, it's much more easy to understand this one-liner and reduce possible errors (like not closing the stream at right time and whatnot). – ALOToverflow Dec 12 '13 at 22:08
  • 3
    Best way because you use a common library offering you: 1) Robustness: People are using this and thus it is validated to work. 2) It does the above (most popular answer) with only 1 line so your code stays clean. 3) Because Dan said so. 4) I'm just kidding regarding to 3 :-) – Lawrence Jan 23 '16 at 08:46
  • 2
    Unfortunately, the method restricts the output size to 1024. If one needs to convert a file to a byte stream, better not use this. – Abilash Jan 26 '16 at 01:11
  • I would not prefer this one for microservices. The library could make them heavier is size, than direct methods. – Zon Nov 02 '19 at 15:03
  • to use ``SerializationUtils.serialize(o)``, your object need this ``implements Serializable`` – TuGordoBello Jul 02 '20 at 15:19
  • @zon so the accepted answer is better than this method if we want to keep the size of the application small? – y_159 May 25 '21 at 04:08
  • @y_159 The accepted answer is a bit outdated. Romero's one is neater as it uses try-with-resources. – Zon May 25 '21 at 09:36
94

If you use Java >= 7, you could improve the accepted solution using try with resources:

private byte[] convertToBytes(Object object) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutputStream 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);
         ObjectInputStream in = new ObjectInputStream(bis)) {
        return in.readObject();
    } 
}
CarlosV
  • 671
  • 2
  • 9
  • 24
Víctor Romero
  • 4,997
  • 1
  • 19
  • 31
8

Can be done by SerializationUtils, by serialize & deserialize method by ApacheUtils to convert object to byte[] and vice-versa , as stated in @uris answer.

To convert an object to byte[] by serializing:

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

To convert byte[] to object by deserializing::

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

Click on the link to Download org-apache-commons-lang.jar

Integrate .jar file by clicking:

FileName -> Open Medule Settings -> Select your module -> Dependencies -> Add Jar file and you are done.

Hope this helps.

Pankaj Lilan
  • 3,638
  • 1
  • 27
  • 44
  • 7
    never add a dependency like this, use maven/gradle to download dependency and add it to the build path – Daniel Bo Jul 30 '19 at 08:06
5

I also recommend to use SerializationUtils tool. I want to make a ajust on a wrong comment by @Abilash. The SerializationUtils.serialize() method is not restricted to 1024 bytes, contrary to another answer here.

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:

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() and toString().

user207421
  • 289,834
  • 37
  • 266
  • 440
gzg_55
  • 51
  • 1
  • 2
  • can you add how to do the reverse? so byte[] to object? I know others have this, but I like your answer a lot more and I can't get the deserialisation to work. I want to avoid returning null in any case. – blkpingu Mar 21 '19 at 20:34
  • I was also skeptical about this code after reading @Abilash answer. But you cleared me. Thanks. – ahrooran Nov 25 '20 at 18:22
4

Another interesting method is from com.fasterxml.jackson.databind.ObjectMapper

byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)

Maven Dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
Asad Shakeel
  • 971
  • 1
  • 12
  • 20
3

If you are using spring, there's a util class available in spring-core. You can simply do

import org.springframework.util.SerializationUtils;

byte[] bytes = SerializationUtils.serialize(anyObject);
Object object = SerializationUtils.deserialize(bytes);
Supun Wijerathne
  • 9,992
  • 6
  • 43
  • 67
1

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();
user207421
  • 289,834
  • 37
  • 266
  • 440
1

Spring Framework org.springframework.util.SerializationUtils

byte[] data = SerializationUtils.serialize(obj);
xxg
  • 1,688
  • 1
  • 8
  • 12
1

In case you want a nice no dependencies copy-paste solution. Grab the code below.

Example

MyObject myObject = ...

byte[] bytes = SerializeUtils.serialize(myObject);
myObject = SerializeUtils.deserialize(bytes);

Source

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();
        }
    }
}
Ilya Gazman
  • 27,805
  • 19
  • 119
  • 190
0

This is just an optimized code form of the accepted answer in case anyone wants to use this in production :

    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 {

    }




}
Nishant_Singh
  • 608
  • 1
  • 6
  • 15
-1

code example with 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;
    }

}

}
Mohamed.Abdo
  • 1,420
  • 16
  • 11