【问题标题】:Save ArrayList to File and searchfor matching IDs将 ArrayList 保存到文件并搜索匹配的 ID
【发布时间】: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


    【解决方案1】:

    如果您使用的是List,则必须对其进行迭代以检查是否存在具有特定 ID 的对象。

    如果您使用的是 Map&lt;String, Student&gt;(如 Andres 所述),其中地图的键是您的 ID,您可以轻松使用 containsKey(String id)

    【讨论】:

      【解决方案2】:

      使用 Map 代替 ArrayList,其中键是 id,值是学生。这将大大简化搜索。

      Map&lt;String, Student&gt; studentMap = new HashMap&lt;String, Student&gt;()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-11
        • 1970-01-01
        • 2022-07-28
        • 2015-04-30
        • 2013-03-21
        • 2016-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多