0

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"?

Razib
  • 10,965
  • 11
  • 53
  • 80
jobr97
  • 179
  • 1
  • 17
  • 1
    I think the new student object is generated based on new line ('\n'), since each student object is printed at a new line. So the **Reader** should process new line, isn't it? – Razib Jan 13 '16 at 18:24
  • reader should read a line and split it using ";" ? – gonephishing Jan 13 '16 at 18:25
  • just checking -- "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" means "I know that the writer is processing line by line. How do I have to code my reader in order to split each line at the semicolons" right? – Leo Jan 13 '16 at 18:26
  • since \n is the entry delimiter, pls be careful and also trim all the strings before printing too – Leo Jan 13 '16 at 18:26

2 Answers2

2

If you are using a more recent version of Java, you could also do this

for (String line : Files.realAllLines(Paths.get(filename)) {
  Student st = new Student();
  String[] data= line.split(";");
  int id = Integer.parseInt(data[0]);
  st.setId(id);
}
Jonathan Beaudoin
  • 2,158
  • 4
  • 27
  • 63
1

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();
redragons
  • 94
  • 4