Why reading byte array to an Object throws java.io.StreamCorruptedException?

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 java.io.StreamCorruptedException: invalid stream header: .

To test the functionality, I wrote following program to convert a String to a byte array and then convert the byte array to an Object .

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

The output is:

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)

Appreciate if someone can help what is wrong here?


Because you corrupted the stream. You shouldn't have had the serialized data in a String in the first place. The round trip back to byte[] is lossy. Just pass the byte[] array around.

Repeat after me. String is not a container for binary data. Write out 100 times ;-)

EDIT 0x54696765 is "Tige". You didn't have a serialized object in the first place. You already had the String .

NB You don't need to close the ByteArrayInputStream if you are closing the wrapping ObjectInputStream , and as that only wraps a ByteArrayInputStream you don't really need to close that either.

链接地址: http://www.djcxy.com/p/33058.html

上一篇: 如何发送Soap消息到activemq队列?

下一篇: 为什么读取字节数组到一个对象会抛出java.io.StreamCorruptedException?