This discussion is archived
13 Replies Latest reply: Jan 2, 2008 12:41 PM by 807601 RSS

Binary I/O - error storing mix of objects and primitives

807601 Newbie
Currently Being Moderated
Hi again, all.

My book told me that
Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputStream with the same types and in the same order as they were written. Java's safe casting should be used to get the desired type.
So I approached the exercise of storing an array of 5 int s, a double , and a Date object like so:
import java.io.*;
import java.util.Date;

public class StoreObjectsAndArrays {
    public static void main(String[] args) throws IOException,
            ClassNotFoundException {
        int[] numbers = {1, 2, 3, 4, 5};
        double dblVal = 5.5;
        Date date = new Date();
        
        ObjectOutputStream output = 
                new ObjectOutputStream(new FileOutputStream("Exercise18_5.dat", true));
        
        output.writeObject(numbers);
        output.writeDouble(dblVal);
        output.writeObject(date);
        
        output.close();
        
        ObjectInputStream input = 
                new ObjectInputStream(new FileInputStream("Exercise18_5.dat"));
        
        int[] newNumbers = (int[])(input.readObject());
        double newDblVal = input.readDouble();
        Date newDate = (Date)(input.readObject());
        
        for (int i = 0; i < newNumbers.length; i++) {
            System.out.print(newNumbers[i] + " ");
        }
        System.out.println();
        System.out.println(newDblVal);
        System.out.println(newDate.toString());
        
        input.close();
    }
}
But I get an error:
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:180)
at java.io.DataInputStream.readLong(DataInputStream.java:399)
at java.io.DataInputStream.readDouble(DataInputStream.java:451)
at java.io.ObjectInputStream$BlockDataInputStream.readDouble(ObjectInputStream.java:2810)
at java.io.ObjectInputStream.readDouble(ObjectInputStream.java:983)
at StoreObjectsAndArrays.main(StoreObjectsAndArrays.java:24)
I can't understand where I got the error, I'm following the process from the book. I'm sure I missed something here, should I do something other than
readDouble()
for the double value?