在原有的学生管理系统中加入两个方法,实现从文件中读取和写入学生信息,代码如下:
//从文件中读数据到集合
public static void readData(String fileName,ArrayList array) throws IOException {
//创建输入缓冲流对象
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while((line=br.readLine())!=null) {
String[] datas = line.split(","); Student s = new Student(); s.setId(datas[0]); s.setName(datas[1]); s.setAge(datas[2]); s.setAddress(datas[3]); array.add(s);
}
br.close();
}
//把集合中的数据写入文件
public static void writeData(String fileName,ArrayList array) throws IOException {
//创建输出缓冲流对象
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
for(int x=0; x<array.size(); x++) {
Student s = array.get(x); StringBuilder sb = new StringBuilder(); sb.append(s.getId()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress()); bw.write(sb.toString()); bw.newLine(); bw.flush();
}
bw.close();
}