package com.n;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class S implements Serializable {
private static final long serialVersionUID = 1L;
transient int i;
public static void main(String[] args) throws Exception, IOException {
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("c:\\jav\\f.txt"));
S obj1 = new S(10);
oos.writeInt(obj1.i);
oos.writeObject(obj1);
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("c:\\jav\\f.txt"));
System.out.println("Object contains >> " + ois.readObject());
System.out.println("Transient variable written separately yields >> i ="
+ ois.readInt());
}
public S(int i) {
this.i = i;
}
@Override
public String toString() {
return "i= " + i;
}
}
The code above throws
Exception in thread "main" java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.n.S.main(S.java:27)
but when I interchange the output lines like
System.out.println("Transient variable written separately yields >> i =" + ois.readInt());
System.out.println("Object contains >> " + ois.readObject());
It runs fine. But why is it so? Do I have to write as well as read the serialized primitive values first and then read or write the object? And what is an OptionalDataException?
You need to read data from an ObjectInputStream in exactly the same order as they were written to the ObjectOutputStream.