我如何通过多次调用从数组列表中存储数据?

问题描述 投票:0回答:1

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

用户应该能够通过特定细节(例如所有名字“jane”)过滤其内容,并将其打印到终端/命令行。我想不断地将数据保存在文件和数组列表中,因为我使用我的getter方法来执行此操作。

我的思路是获取存储在文件中的数据,并在每次运行main函数时将其解析回数组列表。鉴于它是一个个性化的列表,我在这方面遇到了麻烦。任何有助于我完成此任务的方法的帮助将不胜感激。

    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.");
        }

    }
java database file arraylist
1个回答
0
投票

如果您还在发布的问题中提供了学生课程代码,那么本来会非常有帮助的,但无论如何......

显然,在main()方法的早期,您使用User输入来填充Student的List接口,然后我假设您已成功将该List的内容写入Text文件。保持这种想法.....

申请结束。现在重新启动它,现在要重新填充List。好吧,基本上你只需要完全按照你在main()方法中所做的那样做。

你怎么做(未经测试!):

确保List<Student> students;在main()方法所在的同一个类中声明为类成员变量。这将使学生变得全局变为整个班级(在所有其他可能的事情中)。现在将以下方法添加到主类中。这种方法将填写学生名单:

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。

© www.soinside.com 2019 - 2024. All rights reserved.