[英]How might i store data from an Array List through multiple invocations?
I am writing a command line app whereby my main function creates an array list, populates it by user input, and then proceeds to add that content into a txt file. 我正在编写一个命令行应用程序,我的main函数创建一个数组列表,通过用户输入填充它,然后继续将该内容添加到txt文件中。 However, every time I run the main function the Array List naturally starts out empty and the data is lost from it.
但是,每次运行main函数时,Array List自然会开始为空,数据会从中丢失。
The user should be able to filter their content by a specific detail(eg all first names "jane") and have it printed to the terminal/command line. 用户应该能够通过特定细节(例如所有名字“jane”)过滤其内容,并将其打印到终端/命令行。 I'd like to keep the data within the file and array list constantly since I am using my getter methods to do this.
我想不断地将数据保存在文件和数组列表中,因为我使用我的getter方法来执行此操作。
My train of thought has been to take the data stored in the file and parse it back into the array list every time the main function has been run. 我的思路是获取存储在文件中的数据,并在每次运行main函数时将其解析回数组列表。 Given that it's a personalized list, I've had trouble doing this.
鉴于它是一个个性化的列表,我在这方面遇到了麻烦。 Any help on an approach to help me with this task would be appreciated.
任何有助于我完成此任务的方法的帮助将不胜感激。
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.");
}
}
What would have been quite helpful is if you also provided the Students Class code within your Posted Question but in any case..... 如果您还在发布的问题中提供了学生课程代码,那么本来会非常有帮助的,但无论如何......
Apparently, earlier in your main() method you took User input to fill a List Interface of Student and then I presume you successfully wrote the contents of that List to a Text file. 显然,在main()方法的早期,您使用User输入来填充Student的List接口,然后我假设您已成功将该List的内容写入Text文件。 Keep this thought.....
保持这种想法.....
The application closes. 申请结束。 Now you restart it and now you want to refill the the List.
现在重新启动它,现在要重新填充List。 Well, basically you just need to do pretty much exactly what you did within the main() method.
好吧,基本上你只需要完全按照你在main()方法中所做的那样做。
How you might do this (Not Tested!):
你怎么做(未经测试!):
Make sure List<Student> students;
确保
List<Student> students;
is declared as a Class Member variable within the very same Class your main() method is located. 在main()方法所在的同一个类中声明为类成员变量。 This will make the students variable global to the entire Class (among all other things possible).
这将使学生变得全局变为整个班级(在所有其他可能的事情中)。 Now add the following method to your main class.
现在将以下方法添加到主类中。 This method will fill the students List:
这种方法将填写学生名单:
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.
}
Note: Don't forget to close your BufferedWriter in your other *writeToFile()** method. 注意:不要忘记在其他* writeToFile()**方法中关闭BufferedWriter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.