gpt4 book ai didi

java - [Java]读取并处理文件

转载 作者:行者123 更新时间:2023-12-01 21:53:34 25 4
gpt4 key购买 nike

我需要编写一个方法来读取和写入 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com