我需要编写一个方法来读取和写入 ArrayList
到一个文件。我已经得到了写入方法:
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();
}
我知道读者正在逐行处理。我必须如何编写阅读器代码才能在分号处分割每一行,以便获得“学生”所需的 5 个对象?
最佳答案
如果您使用的是更新版本的 Java,也可以执行此操作
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);
}
关于java - [Java]读取并处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34774156/