This article shows how to convert an object to byte[] or byte array and vice versa in Java.

1. Convert an object to byte[]

The below example show how to use ByteArrayOutputStream and ObjectOutputStream to convert an object to byte[].

 // Convert object to byte[]
  public static byte[] convertObjectToBytes(Object obj) {
      ByteArrayOutputStream boas = new ByteArrayOutputStream();
      try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
          ois.writeObject(obj);
          return boas.toByteArray();
      } catch (IOException ioe) {
          ioe.printStackTrace();
      }
      throw new RuntimeException();
  }

  // Convert object to byte[]
  public static byte[] convertObjectToBytes2(Object obj) throws IOException {
      ByteArrayOutputStream boas = new ByteArrayOutputStream();
      try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
          ois.writeObject(obj);
          return boas.toByteArray();
      }
  }

2. Convert byte[] to object

The below example show how to use ByteArrayInputStream and ObjectInputStream to convert byte[] back to an object.

  // Convert byte[] to object
  public static Object convertBytesToObject(byte[] bytes) {
      InputStream is = new ByteArrayInputStream(bytes);
      try (ObjectInputStream ois = new ObjectInputStream(is)) {
          return ois.readObject();
      } catch (IOException | ClassNotFoundException ioe) {
          ioe.printStackTrace();
      }
      throw new RuntimeException();
  }

  // Convert byte[] to object
  public static Object convertBytesToObject2(byte[] bytes)
      throws IOException, ClassNotFoundException {
      InputStream is = new ByteArrayInputStream(bytes);
      try (ObjectInputStream ois = new ObjectInputStream(is)) {
          return ois.readObject();
      }
  }

  // Convert byte[] to object with filter
  public static Object convertBytesToObjectWithFilter(byte[] bytes, ObjectInputFilter filter) {
      InputStream is = new ByteArrayInputStream(bytes);
      try (ObjectInputStream ois = new ObjectInputStream(is)) {

          // add filter before readObject
          ois.setObjectInputFilter(filter);

          return ois.readObject();
      } catch (IOException | ClassNotFoundException ioe) {
          ioe.printStackTrace();
      }
      throw new RuntimeException();
  }

Further Reading

Java Serialization and Deserialization examples

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/object

References

Leave a Reply

Your email address will not be published. Required fields are marked *