Java Custom Serialization throwing EOFException



以下代码在反序列化期间抛出EOFException[行大小= in.readInt((;]我很困惑为什么会发生这种情况。

import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.ArrayList;
public class ArrayList2 implements Serializable
{
    transient String [] bs = new String[100];
    transient int size;
    // custom serialiation (the physical structure is not equal to logical structure)
    private void writeObject(java.io.ObjectOutputStream out)
            throws IOException
    {
        out.defaultWriteObject();
        out.write(size);
        for (int i=0;i<size;i++)
            out.writeObject(bs[i]);
    }
    private void readObject(java.io.ObjectInputStream in)
            throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        size = in.readInt(); // ERROR OCCURS HERE
        bs = new String[size];
        for (int i = 0; i < size; i++)
            bs[i] = (String) in.readObject();
    }
}

有趣的是,当大小不是瞬态的并且我不在 readObject 和 writeObject 中读取或写入大小时,反序列化工作正常。

有什么想法吗?

out.write(size);

问题就在这里。这只写入一个字节。为了与您的阅读代码对称,它应该是

out.writeInt(size);

最新更新