Serialization:java.io.StreamCorruptedException: invalid stream header: 0AACED00

前端 未结 2 1188
半阙折子戏
半阙折子戏 2021-01-18 17:02

I\'m a student practicing my File IO skills and I am coming up against a problem with reading Objects from a file using ObjectInputStream. The code is consistently throwing

相关标签:
2条回答
  • 2021-01-18 17:26
     java.io.StreamCorruptedException: invalid stream header: 0AACED00 
    

    This is caused by appending to the FileOutputStream. As I mentioned in a comment above, you can't append to a stream written by ObjectOutputStream, at least not without special measures. Keep the file and the ObjectOutputStream open until you've written all the objects you want to write, then close it, then deserialize from it.

    NB As I also mentioned,

    while ((object = in.readObect()) != null)
    

    is not a valid object-reading loop. readObject() doesn't return null at end of stream: it throws EOFException. null can occur anywhere in the stream, any time you write one. The correct form of the loop is:

    try
    {
        for (;;)
        {
            Object object = in.readObject();
            // ...
        }
    }
    catch (EOFException exc)
    {
        // end of stream
    }
    // other catch blocks ...
    

    NB 2 This:

    oos.writeObject(object + "\n");
    

    should be just

    oos.writeObject(object);
    

    Otherwise you're implicity calling toString() and pointlessly appending a line terminator, so the result of readObject() will be a String, not the original object.

    0 讨论(0)
  • 2021-01-18 17:40

    I think this was caused by the lack of a serialVersionUID.

    Whenever you serialize an object, the ClassLoader needs something to verify the new loaded object against to verify it and ensure its compatibility. In order to do this, you just need to define a field in your class like this:

    private static final long serialVersionUID = 12358903454875L;
    

    Your IDE may have also given you a warning stating the lack of it (Eclipse does this).

    This should solve your problem.

    You can learn more in this excellent answer by Jon Skeet here: What is a serialVersionUID and why should I use it?.

    0 讨论(0)
提交回复
热议问题