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();
}
}
}
CodePudding user response:
You get an EOFException
because you've reached the End of the File.
For some reason you assume that in.readObject()
will return null
when it reached the end of the input, but that's not how it's specified.
You can either just use the EOFException
as flow control (i.e. just let it happen in the flow of normal operation) or change to a format where you don't have to guess if more objects are available. The simplest way to do the second thing is to just write the whole array instead of individual people:
Replace your writing loop with just
out.writeObject(people);
And your reading loop with something like this:
Person[] readPeople = (Person[]) in.readObject();
for (int i = 0; i < readPeople .length; i ) {
System.out.println(readPeople[i]);
}