2016-01-13 88 views
0

我需要写读写的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个对象?

+1

我认为新学生对象是基于新行('\ n')生成的,因为每个学生对象都以新行打印。所以** Reader **应该处理新行,不是吗? – Razib

+0

阅读器应该读一行并使用“;”分隔它? – gonephishing

+0

只是检查 - “我知道读者是通过线加工生产线我如何有以拆分在分号每一行的代码我的读者”的意思是“我知道,作家是以线加工生产线怎么办。我必须对我的阅读器进行编码,以便以分号分隔每行“对吧? – Leo

回答

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

如果您使用的更近的一个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); 
}