Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OptionalDataException in java

Tags:

java

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?

like image 674
Nav Avatar asked Dec 25 '11 16:12

Nav


2 Answers

You need to read data from an ObjectInputStream in exactly the same order as they were written to the ObjectOutputStream.

like image 124
Ted Hopp Avatar answered Oct 03 '22 21:10

Ted Hopp


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!

like image 31
aishwarya Avatar answered Oct 03 '22 22:10

aishwarya