I'm trying to read objects from a file that I have written to but when reading there's an EOFException that gets thrown. I can see that it reads the objects but halfway through reading the file the error shows up.
public class IOStream { /** * @param args the command line arguments */ public static void main(String[] args) throws ClassNotFoundException { Person[] people = new Person[14]; people[0] = new Professor("Professor", "Issac", "Newton", "Physcis", 6); people[1] = new TA("TA", "Marie", "Curie", "Physics", 6); people[2] = new Professor("Professor", "Issac", "Newton", "Calculus", 4); people[3] = new Student("Student", "Amy", "Adams", "Calculus", 4); people[4] = new Student("Student", "Will", "Smith", "Calculus", 4); people[5] = new Student("Student", "Brad", "Pitt", "Physics", 6); people[6] = new Student("Student", "Will", "Smith", "Physics", 6); people[7] = new Professor("Professor", "Dimitri", "Mendeleev", "Chemistry", 6); people[8] = new TA("TA", "Carl", "Gauss", "Calculus", 4); people[9] = new Student("Student", "Amy", "Adams", "Economics", 3); people[10] = new Professor("Professor", "Adam", "Smith", "Economics", 3); people[11] = new TA("TA", "Marie", "Curie", "Chemistry", 6); people[12] = new Student("Student", "Brad", "Pitt", "Chemistry", 6); people[13] = new Student("Student", "Will", "Smith", "Chemistry", 6); //WRITING try ( ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream("object.txt")))) { for (int i = 0; i < people.length; i++) { out.writeObject(people[i]); } out.close(); } catch (IOException e) { e.printStackTrace(); } try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream( new FileInputStream("object.txt")))){ Person lol; while ((lol = (Person)in.readObject())!= null){ System.out.println(lol); } } catch(EOFException i){ i.printStackTrace(); System.out.println("End of File"); } catch (IOException e){ e.printStackTrace(); } } }
.txtextension for files containing serialized data, because it will not be readable text in any meaningful way. I've seen.seror.objor.datused, it's not that important, but.txtimplies that the file contains human-readable text which is barely the case with these files.Person[] people = { new Professor(), new TA(), new Student() }(no need for indexes) - you don't need to manually close a stream in a try-with-resources statement, so you can remove the call toout.close()- you can use the "for each" notationfor (Person p : people) { out.writeObject(p); }instead offor (int i = 0; i < people.length; i++) { out.writeObject(people[i]); }for clarity