【问题标题】:java.io.StreamCorruptedException: invalid type code: 3F when I customize serialization processjava.io.StreamCorruptedException:无效类型代码:自定义序列化过程时为 3F
【发布时间】:2014-07-03 14:33:37
【问题描述】:

请帮助了解序列化问题的原因。

我有以下目标类声明:

class Line implements Serializable {
    int index;

    public Line() {
        System.out.println("Constructing empty line");
    }

    Line( int index) {
        System.out.println("Constructing line: " + index);
        this.index = index;
    }

    //get and set

    public void printInfo() {
        System.out.println("Line: " + index);
        System.out.println(" Object reference: " + super.toString());         
    }
}

以下主要内容:

            ...

            FileOutputStream os = new FileOutputStream(fileName);
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(line1);
            oos.close();
            System.out.println("Read objects:");
            FileInputStream is = new FileInputStream(fileName);
            ObjectInputStream ois = new ObjectInputStream(is);

            Line line = (Line) ois.readObject();
            line.printInfo();

            ois.close();
            ...

此代码运行良好,但如果我添加到目标类以下方法:

    private void writeObject(ObjectOutputStream oos) throws IOException {
        // default serialization
        System.out.println("custom serialization!!!!");
        oos.defaultWriteObject();
    }

    private void readObject(ObjectInputStream objectInputStream) throws
            IOException, ClassNotFoundException {
        System.out.println("custom Deserialization!!!!");
        objectInputStream.readObject();
    }

我明白了:

java.io.StreamCorruptedException: invalid type code: 00
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
    at io_nio.Line.readObject(SerializationWithReferencesToComplicatedObjects.java:164)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    ...

问题的原因是什么?

【问题讨论】:

    标签: java serialization io customization


    【解决方案1】:

    您应该在您的readObject() 方法中调用ObjectInputStream.defaultReadObject()。不是ObjectInputStream.readObject()

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      相关资源
      最近更新 更多