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.
please see the definition of the exception: http://docs.oracle.com/javase/6/docs/api/java/io/OptionalDataException.html
You have a primitive before an object as stored (you wrote int before object). The document says:
An attempt was made to read an object when the next element in the stream is primitive data. In this case, the OptionalDataException's length field is set to the number of bytes of primitive data immediately readable from the stream, and the eof field is set to false.
so yes, you need to readInt first.
HTH!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With