0
請幫助理解序列化問題的原因。java.io.StreamCorruptedException:無效類型代碼:3F當我自定義序列化過程
我有以下目標類聲明:
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)
...
問題的原因是什麼?
真的很愚蠢的錯誤。 – gstackoverflow