13 Replies Latest reply on Jan 3, 2008 12:04 AM by EJP

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

      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));
              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] + " ");
      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
      for the double value?