Java——字符缓冲流练习之集合到文件、文件到集合、点名器

一、集合到文件(集合中的数据是字符串)

1、需求

把ArrayList集合中的字符串数据写入到文本文件,要求每一个字符串元素作为文件中的一行数据

2、思路

  • 创建ArrayList集合
  • 往集合里存储字符串元素
  • 创建字符缓冲输出流对象
  • 遍历集合,得到每一个字符串数据
  • 调用字符缓冲输出流对象的方法写数据
  • 释放资源

3、代码实现

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Demo1 {
   
    public static void main(String[] args) throws IOException {
   
        ArrayList<String> array = new ArrayList<String>();
        array.add("hello");
        array.add("world");
        array.add("java");
        BufferedWriter bw = new BufferedWriter(new FileWriter("ZiFuLiu\\array.txt"));
        for (String arr:array){
   
            bw.write(arr);
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }
}

二、集合到文件(集合中的数据是学生对象)

1、需求

把ArrayList集合中的学生数据写入到文本文件,要求每一个学生对象的数据作为文件中的一行数据

格式:学号,姓名,年龄,居住地

2、思路

  • 定义学生类
  • 创建ArrayList集合
  • 创建学生对象
  • 把学生对象添加到集合中
  • 创建字符缓冲输出流对象
  • 遍历集合,得到每一个学生对象
  • 将学生对象的数据拼接成指定格式的字符串
  • 调用字符缓冲输出流对象的方法写数据
  • 释放资源

3、代码实现

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Demo {
   
    public static void main(String[] args) throws IOException {
   
        ArrayList<Student> array = new ArrayList<Student>();
        Student s1 = new Student("001", "zlx", 18, "天津");
        Student s2 = new Student("002", "dfv", 13, "北京");
        Student s3 = new Student("003", "vgb", 25, "深圳");
        Student s4 = new Student("004", "huj", 24, "上海");
        array.add(s1);
        array.add(s2);
        array.add(s3)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值