I'm writing an application which on the one end writes objects to a binary file and on the other end reads these objects from the same binary file.
The writing to file works perfectly and when opening the .dat file in notepad it's clear the objects are being written as intended.
But trying to loop through them and reading them seems to be a bit of a problem. I'm using the while (true) loop as below but only the first object gets returned.
Could it be that it's not writing it correctly to file?
The code to write to file is as follows:
try {
outputStream.writeObject(newObj);
outputStream.close();
System.out.println("Obj written to file.");
}
catch(IOException e) {
System.out.println("Error writing to file " + FILE);
System.exit(0);
}
and to read from file:
try {
inputStream = new ObjectInputStream(new FileInputStream(FILE));
}
catch(IOException e) {
System.out.println("Error opening file " + FILE + ".");
System.exit(0);
}
try {
while (true) {
obj pet = (obj)inputStream.readObject();
obj.writeOutput();
}
}
catch(EOFException e) {
System.out.println("End of reading from file.");
}
catch(IOException e) {
System.out.println("End of reading from file.");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found.");
}
Please let me know how to loop through all the objects present.