【问题标题】:[Java ]read & process file [duplicate][Java ]read & process file [duplicate]
【发布时间】:2016-04-18 20:50:03
【问题描述】:

我需要编写一个方法来读取ArrayList 并将其写入文件。我已经有了write方法:

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 个对象?

【问题讨论】:

  • 我认为新的学生对象是基于换行('\n')生成的,因为每个学生对象都打印在新行。所以 Reader 应该处理新行,不是吗?
  • 读者应该阅读一行并使用“;”分割它?
  • 只是检查——“我知道阅读器正在逐行处理。我如何编写阅读器以便在分号处分割每一行”意思是“我知道作者是逐行处理。我如何对阅读器进行编码才能在分号处分割每一行?
  • 由于 \n 是条目分隔符,请注意并在打印前修剪所有字符串

标签: java file io filereader reader


【解决方案1】:

如果您使用的是更新版本的 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);
}

【讨论】:

    【解决方案2】:

    您可以创建一个 BufferedReader 并在逐行读取时,使用“;”分割行并根据这些值构造 Student 对象。当然,当您这样做时,您必须知道结果数组中的哪个索引包含哪些信息,例如:

    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();
    

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 2013-12-22
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多