0

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. However, every time I run the main function the Array List naturally starts out empty and the data is lost from it.

The user should be able to filter their content by a specific detail(e.g all first names "jane") and have it printed to the terminal/command line. I'd like to keep the data within the file and array list constantly since I am using my getter methods to do this.

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

    }
  • You can serialize the data to the file then deserialize back from the file. https://www.mkyong.com/java/how-to-read-and-write-java-object-to-a-file/ – DCTID Apr 12 '19 at 02:53
  • The method `writeToFile()` writes the student data to a file. Did you open the file and see if it has written? Can you share a sample of the file contents? – prasad_ Apr 12 '19 at 04:50
  • Did you try searching on Google; I found this useful post with the the search string "java store list data to file": [How Can I Write My ArrayList to a file, and Read that file to the original ArrayList?](https://stackoverflow.com/questions/16111496/java-how-can-i-write-my-arraylist-to-a-file-and-read-load-that-file-to-the). There are some other useful posts out there. – prasad_ Apr 12 '19 at 06:28

1 Answers1

0

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. Keep this thought.....

The application closes. Now you restart it and now you want to refill the the List. Well, basically you just need to do pretty much exactly what you did within the main() method.

How you might do this (Not Tested!):

Make sure List<Student> students; is declared as a Class Member variable within the very same Class your main() method is located. 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.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22