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

标签 java file io filereader reader

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

相关文章:

c - 将文件写入结构体数组

php - 如何在 SHTML 页面中包含 PHP 文件?

file - 尝试使用 io.WriteString 写入文件时出现 Golang "Access is denied"错误

io - Prolog:将用户输入作为参数传递

postgresql - Cassandra 如何处理磁盘 IO

java - Java中的方法不起作用?

java - 如果每个异常捕获都应该记录它?

java - 如何对类型为 <Entry<Character, Integer>> 的 ArrayList 进行排序?

python - 在 Python 中读取带有行连续字符的文件

Java泛型,类型丢失