[Java]阅读&处理文件

时间:2016-01-13 18:18:52

标签: java file io filereader reader

我需要编写一个方法来读取和写入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(); } 到文件。我已经有了写方法:

{{1}}

我知道读者正在逐行处理。我如何编写我的阅读器代码,以分号分隔每一行,以便得到#34;学生&#34;所需的5个对象?

2 个答案:

答案 0 :(得分:2)

如果您使用的是更新版本的Java,也可以执行此操作

(Transaction.Parameters["Test"].Value is equal to Test)

答案 1 :(得分:1)

您可以创建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();