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?
- Why am I getting this exception?
- Plane is serializable. Is it possible to read and write to file if I changed Plane to be parcable instead? (How?)