0

I am trying to read/write an ArrayList of custom (serializable) objects to a file. It is working as expected, except for one thing: I am getting an EOFexception when reading the file. Here is my code:

class FileHandler {
    private final String FILENAME = "storage.txt";

    ArrayList<Plane> readFromFile(Context context) {
        ArrayList<Plane> returnList = new ArrayList<>();
        Plane temp;

        try {
            FileInputStream fileInputStream = context.openFileInput(FILENAME);
            ObjectInputStream objectInStream = new ObjectInputStream(fileInputStream);


            while ((temp = (Plane)objectInStream.readObject()) != null) {
                returnList.add(temp);
            }

            objectInStream.close();
        }
        catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return returnList;
    }

    void writeToFile(ArrayList<Plane> inData, Context context) {
        FileOutputStream fileOutputStream;
        ObjectOutputStream outputStream;

        try {
            fileOutputStream = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            outputStream = new ObjectOutputStream(fileOutputStream);

            for (Plane p: inData) {
                outputStream.writeObject(p);
            }

            outputStream.close();
            fileOutputStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The file gets written and read as intended, but I'm getting an EOF exception when reading the file. No idea why. I thought my while-loop would make sure that couldn't happen?

  1. Why am I getting this exception?
  2. Plane is serializable. Is it possible to read and write to file if I changed Plane to be parcable instead? (How?)

1 Answers1

0

Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions. If there is no corresponding writeObject method, then the end of default serialized data marks the end of the allotted data.

This is what I found on https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html

The last attempt to read data occurs when there is no data. The while-loop condition doesn't really check whether there is data to read or not. It tries to read it regardless.

dhani
  • 31
  • 1
  • 4
  • How do I perform such a check? –  Oct 29 '17 at 20:15
  • https://stackoverflow.com/questions/2626163/java-fileinputstream-objectinputstream-reaches-end-of-file-eof This might be useful – dhani Oct 30 '17 at 04:51