Search code examples
javafileiofilereaderreader

[Java ]read & process file


I need to write a method to read and write an ArrayList to a file. I already got the write method:

public void saveToFile(String file, ArrayList<Student> arrayList) throws IOException {
        int length = arrayList.size();

        FileWriter fileWriter = new FileWriter(file);

        for (Student student : arrayList){
            int id = student.getId();
            String name = student.getName();
            int rep = student.getAnzahlRepetitonen();
            double wahrscheinlichkeit = student.getWahrscheinlichkeit();
            boolean inPot = student.isInPot();

            fileWriter.write(Integer.toString(id) + "; " + name + "; " + Integer.toString(rep) + "; " + Double.toString(wahrscheinlichkeit) + "; " + Boolean.toString(inPot) + "\n");
        }

        fileWriter.close();
    }

I know that the reader is processing line by line. How do I have to code my reader in order to split each line at the semicolons so I get the 5 objects needed for a "Student"?


Solution

  • You can create a BufferedReader and while reading line by line, split the line using ";" and construct the Student object based on those values. Of course, when you do that you have to know what index in the resulting array holds which information like:

    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line = null;
    while ((line = br.readline()) != null) {
          Student st = new Student();
          String[] cols = line.split(";");
          int id = Integer.parseInt(cols[0]);
          st.setId(id);
          // .. so on for other indices like cols[1] etc..
    }
    br.close();