IO流案例:写入学生对象

/*

  • 字符流的练习之把集合中的学生对象数据存储到文本文件
  • 文本文件中的内容 :
  • 张三,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();

	}

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值