我正在创建一个图形用户界面,并使用学生对象返回数据类型的"getStudentInfo()“方法从学生检索信息,并将它们存储到”JTextFields“对象中。
public Student getStudentInfo() {
Student student = new Student();
String name = jtfName.getText();
student.setName(name);
String idNumber = jtfIDNumber.getText();
student.setIdNumber(idNumber);
String address = jtfAddress.getText();
student.setAddress(address);
String phoneNumber = jtfPhoneNumber.getText();
student.setPhoneNumber(phoneNumber);
String major = jtfMajor.getText();
student.setMajor(major);
return student;
}然后,在另一个类中,我创建了一个" add“按钮,当单击该按钮时,应该将”ArrayList“对象添加到一个ArrayList中,然后将该file写入一个二进制文件。
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
File studentFile = new File(FILENAME);
ArrayList<Student> studentList = new ArrayList<Student>();
studentList.add(text.getStudentInfo());
try {
FileOutputStream fos = new FileOutputStream(studentFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
}
catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}但是当我运行程序时,我写下了一个学生的信息,并将其添加到二进制文件中,然后我去添加另一个学生,它完全覆盖了前一个学生的信息。任何帮助都将不胜感激。
发布于 2014-03-07 11:15:27
在您的类AddButtonListener的actionPerformed方法中,您有下面一行代码:
FileOutputStream fos = new FileOutputStream(studentFile);此构造函数将打开文件,因此字节将写入文件的开头。由于每次单击该按钮时都会重新打开此文件,因此您将用新数据替换文件内容。相反,使用带有布尔参数的构造函数来追加字节,而不是覆盖...
FileOutputStream fos = new FileOutputStream(studentFile, true);您可以在java文档中查看此构造函数的详细信息...
FileOutputStream constructor documentation
https://stackoverflow.com/questions/21870684
复制相似问题