【发布时间】:2014-02-04 10:18:59
【问题描述】:
我正在尝试制作一个程序,其中用户将个人信息输入到表单中,该表单被保存为带有字符串变量的 ArrayList 对象并将其保存到文件中。我希望即使程序关闭也能保存这个文件,当一个新人输入他们的信息时,它会创建一个新的 ArrayList 并附加到文件中。
我的问题是尝试创建一个“搜索”功能,让您搜索您的 ID 号并确定您的信息是否已经在文件中。这是我的 ActionListener 方法:
public void actionPerformed(ActionEvent e)
{
strID = tfID.getText();
strName = tfName.getText();
strYear = tfYear.getText();
strSubject = tfSubject.getText();
dblGPA = Double.parseDouble(tfGPA.getText());
strComment = tfComment.getText();
Student newStudent = new Student(strID, strName, strYear, strSubject, dblGPA, strComment);
ArrayList<Student> studentInfo = new ArrayList<Student>();
studentInfo.add(newStudent);
try {
writeFile(studentInfo);
System.out.println(loadFile().toString());
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
然后是我的 Write 和 Read 方法:
public static void writeFile(ArrayList<Student> studentInfo) throws IOException {
FileOutputStream fos = new FileOutputStream(new File("studentlog.dat"), true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentInfo);
oos.close();
}
public static ArrayList<Student> loadFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(new File("studentlog.dat"));
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Student> sAL = (ArrayList<Student>) ois.readObject();
ois.close();
return sAL;
}
现在我只需要一个用于搜索按钮的 ActionListener 方法,该方法将从 JTextField tfSearch 中搜索 ID 号,然后将其与文件中的现有 ID 号进行比较。我觉得我做错了什么可怕的错误,但这可能只是一个愚蠢的错误。
【问题讨论】:
标签: java search arraylist binaryfiles