When you write multiple objects with an ObjectOutputStream
, it makes a block data record that stores the information about the objects. If at any point you then close the stream and later reopen it to write more objects, the block data record will be overwritten. Every time you call writedata
this problem occurs. You also do not open the file in append mode, so it simply replaces the existing data, but this would still cause problems here.
But there is a better way that fixes this issue and will let you generalise your code to many students
. Keep making your objects, and then store them all in a List
, and just write the single List
object to file. The serialization process will write all the members of the list to file too.
You should capitalise names of classes, but I will stick with your class name here:
List<student> studentList = new ArrayList<>();
for (int i = 0; i < n; ++i) {
System.out.println("Student first name: ");
String fName = input.next();
System.out.println("Student last name: ");
String lName = input.next();
System.out.println("Enter ID: ");
int id = input.nextInt();
System.out.println("Enter gpa: ");
byte gpa = input.nextByte();
student stu = new student();
//setting these fields with a constructor to would be better
stu.first = fName;
stu.last = lName;
stu.id = id;
stu.gpa = gpa;
studentList.add(stu);
}
//this part is serializing the list and writing it to file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
System.out.println("Writing information");
oos.writeObject(studentList);
oos.close();
System.out.println("Done");
//this part deserializes the list from file, and then iterates over its members
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
System.out.println("reading object");
List<student> list = (List) ois.readObject();
System.out.println("done reading object");
for (student stu : list) {
System.out.println(stu.first);
System.out.println(stu.last);
System.out.println(stu.id);
System.out.println(stu.gpa);
}
The code above will overwrite the existing file each time it is run, but I leave that to you. Your code may also have other issues.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…