title: Why reading byte array to an Object throws java.io.StreamCorruptedException?
body: <p>I have a requirement to read a stream of bytes from a remote system. The remote system has its own client API to read the bytes. But at my end, I have to convert the byte array to a POJO. While doing so, I am getting error <code>java.io.StreamCorruptedException: invalid stream header:</code>.</p>
  
  <p>To test the functionality, I wrote following program to convert a <code>String</code> to a <code>byte array</code> and then convert the byte array to an <code>Object</code>.</p>
  
  <pre>
  public class ByteToObject {
    public static void main(String[] args) {
      try {
        final String str = "Tiger";
        System.out.println("\nByte array for string '" + str + "' --> \n" + Arrays.toString(getByteArray(str)));
        System.out.println("Object read --> " + getObject(getByteArray(str)));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  
    private static byte[] getByteArray(final String str) throws Exception {
      return str.getBytes(CharEncoding.UTF_8);
    }
  
    private static Object getObject(final byte[] byteArray) throws Exception {
      InputStream byteArrayStream = null;
      ObjectInputStream inputStream = null;
  
      try {
          byteArrayStream = new ByteArrayInputStream(byteArray);
          inputStream = new ObjectInputStream(byteArrayStream);
          return inputStream.readObject();
        } finally {
          if(null != byteArrayStream) {
            byteArrayStream.close();
          }
          if(null != inputStream) {
            inputStream.close();
          }
       } 
    }
  }
  </pre>
  
  <p>The output is:</p>
  
  <pre>
  Byte array for string 'Tiger' --> 
  [84, 105, 103, 101, 114]
  java.io.StreamCorruptedException: invalid stream header: 54696765
  Object read --> null
      at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
      at java.io.ObjectInputStream.(ObjectInputStream.java:299)
      at com.demo.serialize.ByteToObject.getObject(ByteToObject.java:41)
      at com.demo.serialize.ByteToObject.main(ByteToObject.java:24)
  </pre>
  
  <p>Appreciate if someone can help what is wrong here?</p>