0

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.

alwynmalan
  • 149
  • 1
  • 1
  • 12
  • I'm not sure that checking the correctness of binary data by using a text editor is the correct way... – Thomas Aug 15 '14 at 07:05
  • 1
    Btw, from your code you seem to serialize only one object to the file, so you could only read one as well. – Thomas Aug 15 '14 at 07:07
  • The writing is on demand. So if you user chooses to write, he enters the specifics and object gets written to file. If he repeats a second etc. get written to file – alwynmalan Aug 15 '14 at 07:14

0 Answers0