/*
- 字符流的练习之把集合中的学生对象数据存储到文本文件
- 文本文件中的内容 :
- 张三,23,男,98
- 李四,24,男,99
- 柳岩,18,女,100
- 分析 :
1 创建学生类 , 姓名 , 年龄 , 性别 , 分数
* 2 创建集合对象
* 3 创建元素对象
* 4 添加元素
* 5 创建高效的字符输出流
* 6 遍历集合,拿到每一个学生对象,在写入文件中 xxx,xxx,xxx,xxx
* 7 关流
*/
public class Demo4 {
public static void main(String[] args) throws IOException {
// 创建集合对象
ArrayList<Student> list = new ArrayList<>();
// 创建元素对象
Student s1 = new Student("张三", 23, "男", 98);
Student s2 = new Student("李四", 24, "男", 99);
Student s3 = new Student("柳岩", 18, "女", 100);
// 添加元素
list.add(s1);
list.add(s2);
list.add(s3);
// 创建高效的字符输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("student.txt"));
// 遍历集合,拿到每一个学生对象,在写入文件中 xxx,xxx,xxx,xxx
// for(Student s : list){
// String stu = s.getName()+","+s.getAge()+","+s.getSex()+","+s.getScore();
// bw.write(stu);
// bw.newLine();
// bw.flush();
// }
for(Student s : list){
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getSex()).append(",").append(s.getScore());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close();
}
}