【发布时间】:2021-03-29 16:18:56
【问题描述】:
到目前为止,我发现有一种方法可以通过创建子类来进行序列化附加,但这似乎是一个漫长的方法。有没有更好的方法在序列化中追加?
我在一个名为 Course
的类中有这个 vectorlistprivate Vector<Student> StudentList = new Vector<>();
我有 2 个课程对象。 3 名学生注册了一门课程,2 名学生注册了另一门课程。现在我调用这个在文件中进行序列化的方法,但是当我用我的第二个课程对象调用它时,它会替换以前的内容。
public void Serialization() {
try {
File file = new File("EnrolledStudentsSerial.txt");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fo = new FileOutputStream(file);
ObjectOutputStream output = new ObjectOutputStream(fo);
output.writeObject("Course: " + this.name + "\n\nEnrolled Students: ");
for (int i = 0; i < StudentList.size(); i++) {
Student p_obj = StudentList.elementAt(i);
String content = "\n\tStudent Name: " + p_obj.getName() + "\n\tStudent Department: " + p_obj.getDepartment() + "\n\tStudent Age: " + p_obj.getAge() + "\n";
output.writeObject(content);
}
output.writeObject("\n");
fo.close();
} catch (IOException ioe){
System.out.println("Error: " + ioe.getMessage());
}
}
【问题讨论】:
标签: java serialization netbeans objectoutputstream