本文介绍了java.io.StreamCorruptedException:无效的类型代码:自定义序列化过程时为3F的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮助了解序列化问题的原因.
Please help to understand cause of problem with serialization.
我有以下Target类声明:
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());
}
}
和以下主要内容:
...
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();
}
我知道了
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)
...
问题的原因是什么?
推荐答案
您应该在readObject()
方法中调用ObjectInputStream.defaultReadObject()
.不是ObjectInputStream.readObject()
.
You should be calling ObjectInputStream.defaultReadObject()
in your readObject()
method. Not ObjectInputStream.readObject()
.
这篇关于java.io.StreamCorruptedException:无效的类型代码:自定义序列化过程时为3F的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!