java.io.StreamCorruptedException: invalid type code: 3F when I customize serialization process

ⅰ亾dé卋堺 提交于 2019-12-11 17:52:08

问题


Please help to understand cause of problem with serialization.

I have following Target class declaration:

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());         
    }
}

and following main:

            ...

            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();
            ...

this code works good but if I add to target class following methods:

    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();
    }

I see:

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)
    ...

What the cause of the problem?


回答1:


You should be calling ObjectInputStream.defaultReadObject() in your readObject() method. Not ObjectInputStream.readObject().



来源:https://stackoverflow.com/questions/24556629/java-io-streamcorruptedexception-invalid-type-code-3f-when-i-customize-seriali

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!