Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

java - ObjectInputStream Invalid Stream Header: 00000000

I want to use a single ObjectInputStream to read from a byte array, but I keep getting a StreamCorruptedException every time I start the program.

public void run(){

        byte[] receiveBuffer = new byte[65535];

        bIn = new ByteArrayInputStream(receiveBuffer);

        try {
            in = new ObjectInputStream(bIn);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        while(true){
            try {
                packetIn = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                sock.receive(packetIn);

                Object o = in.readObject();
                //do things with o
            }
        }
}

I'm just trying to initialize the ObjectInputStream to read from the byte array eventually, but it's throwing that exception even if I remove the while loop.

What am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you take a look at the javadocs for the ObjectInputStream(InputStream) constructor, you'll see:

Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.

...

throws

    StreamCorruptedException - if the stream header is incorrect

(emphasis added)

In other words, the constructor doesn't just record the InputStream reference you give it, it also reads from that object. In this case, that's a stream of all 0s.

You should defer creating the ObjectInputStream until you have the serialized data (or at least enough of it to read the header).

(In the interest of "teach a person to fish," I'll also note that any time a method/constructor throws an exception you don't expect, that method's javadocs are a good place to start for understanding its behavior. The javadocs for the JDK classes are usually pretty good.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...