java.io.StreamCorruptedException:意外重置;递归深度1

时间:2014-04-09 02:24:36

标签: java serialization objectoutputstream

我试图在两个线程中使用ObjectInputStream和ObjectOutputStream来写入和读取一个文件。由于我必须附加到这个文件,所以根据一些在线建议,我实现了一个类:

public class AppendableObjectOutputStream extends ObjectOutputStream {

public AppendableObjectOutputStream(OutputStream out) throws IOException {
    super(out);
}

protected void writeStreamHeader() throws IOException {
    reset();
}
}

写逻辑就像:

synchronized (SDKLogger.failoverFile) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            if (failoverFile.exists()) {
                fos = new FileOutputStream(SDKLogger.failoverFile, true);
                oos = new AppendableObjectOutputStream(fos);
            } else {
                fos = new FileOutputStream(SDKLogger.failoverFile, true);
                oos = new ObjectOutputStream(fos);
            }
            for (LogModel log : logs)
                oos.writeObject(log);

因为我已经同步了仅用于此目的的全局文件,而没有在其他任何地方引用,我不明白为什么我总是遇到这个例外。

java.io.StreamCorruptedException: unexpected reset; recursion depth: 1
at java.io.ObjectInputStream.handleReset(Unknown Source)
at java.io.ObjectInputStream.access$600(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.refill(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.skipBlockData(Unknown Source)
at java.io.ObjectInputStream.skipCustomData(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source) 

在搜索网页后,我几乎找不到关于这个错误的内容以及为什么会遇到这个错误。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

reset()中呼叫writeStreamHeader()完全没有意义。此时您仍在构建对象流:它中没有任何内容可以重置。这显然也是这个问题的根源。只需删除它。