如何通过多次调用存储阵列列表中的数据?

时间:2019-04-12 01:29:48

标签: java database file arraylist

我正在编写一个命令行应用程序,由此我的主要功能创建一个数组列表,并通过用户输入填充它,然后继续将该内容添加到txt文件中。但是,每次我运行主函数时,数组列表自然会开始为空,并且数据从中丢失。

用户应该能够按特定的详细信息(例如所有名字“ jane”)过滤其内容,并将其打印到终端/命令行中。由于我正在使用getter方法来执行此操作,因此我希望将数据始终保持在文件和数组列表中。

我的思路是每次运行主要功能时,将存储在文件中的数据提取并解析回数组列表中。考虑到这是一个个性化列表,我在执行此操作时遇到了麻烦。任何对我有帮助的方法的帮助将不胜感激。

    public void writeToFile(String fileName, List<Student> students) {
        try {
            BufferedWriter printToFile = new BufferedWriter(new FileWriter(fileName, true));
            for (Student student: students) {
                printToFile.write(student.toString() + "\n");

            }
            System.out.println("Successfully Written To File!");
            printToFile.close();
        }

        catch (IOException Exception) {
            System.out.println("Error: File Not Found");
        }
    }   




    public void openFile(String fileName) {

        try{
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line=reader.readLine())!=null)
            {
                System.out.println(lin);

            }

        }
        catch (IOException fileNotFound) {
            System.out.println("File Not Found.");
        }

    }

1 个答案:

答案 0 :(得分:0)

如果您在发帖问题中也提供了 学生 班级代码,那将是很有帮助的,但是无论如何.....

很显然,在您的 main()方法中,您之前曾用过User输入来填写Student的List接口,然后我假设您已成功将该List的内容写入了Text文件。保持这个想法.....

应用程序关闭。现在重新启动它,现在您想重新填充列表。好吧,基本上,您只需要非常精确地完成您在 main()方法中所做的工作即可。

  

如何执行此操作(未经测试!):

确保在您的 main() 方法所在的同一类中,将List<Student> students;声明为Class Member变量。这将使 students (学生)变量对整个班级都是全局的(可能的话)。现在,将以下方法添加到您的主类。该方法将填充学生列表:

public static int loadStudentData(String fileName) {
    // Create a List to hold file data;
    List<String> dataList = new ArrayList<>();

    // Fill The Data List.
    // Use 'Try With Resources' to auto-close the BufferedReader.
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        while ((line = reader.readLine()) != null) {
            // Skip blank lines (if any);
            if (line.trim().equals("")) {
                continue;
            }
            dataList.add(line);
        }
    }
    catch (IOException fileNotFound) {
        System.out.println("File Not Found.");
    }

    /* 
      Now that you have all the Student Data from file you can
      Fill in Student instance objects and add them to the students
      List Object

      Keep in mind, I have no idea what constructor(s) or 
      what Getters and Setters you have in your Student 
      Class OR what is contained within the data file so 
      we'll keep this real basic.
    */

    // Declare an instance of Student.
    Student student;
    // Number of students to process
    int studentCount = dataList.size(); 

    // Just in case...clear the students List if it contains anything.
    if (students != null || students.size() > 0) {
        students.clear();
    }

    // Iterate through the list holding file data (dataList)
    for (int i = 0; i < studentCount; i++) {
        student = new Student(); // initialize a new Student
        // Assuming each data line is a comma delimited string of Student data
        String[] studentData = dataList.get(i).split(",|,\\s+");
        student.setStudentID(studentData[0]);                     // String
        student.setStudentName(studentData[1]);                   // String
        student.setStudentAge(Integer.parseInt(studentData[2]));  // Integer
        student.setStudentGrade(studentData[3]);                  // String

         // Add this instance of Student to the students List.
        students.add(student);
    }

    // Return the number of students processed (just in case you want it).
    return studentCount; 
    // DONE.
} 

注意:别忘了用其他* writeToFile()**方法关闭BufferedWriter。