gpt4 book ai didi

Java 自定义序列化抛出 EOFException

转载 作者:行者123 更新时间:2023-12-02 11:30:46 25 4
gpt4 key购买 nike

以下代码在反序列化期间抛出 EOFException [in line size = 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();

}
}

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

有什么想法吗?

最佳答案

out.write(size);

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

out.writeInt(size);

关于Java 自定义序列化抛出 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49310430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com