把ArrayList集合中的学生数据写入到文本文件

    public static void main(String[] args) throws IOException {
        // 创建 ArrayList集合
        ArrayList<Student> stus = new ArrayList<>();
        stus.add(new Student("ID001","张三",30,"北京"));
        stus.add(new Student("ID002","李四",31,"上海"));
        stus.add(new Student("ID003","王五",32,"深圳"));


        // 创建缓冲输出流
        BufferedWriter bw = new BufferedWriter(new FileWriter("day12_javaOOP_io_buffer&print&properties\\stus.txt"));

        // 写数据
        // 遍历集合
        for (Student stu : stus) {
            // 创建sb对象,拼接ID001,张三,30,北京格式
            StringBuilder sb = new StringBuilder();
            sb.append(stu.getSid()).append(",").append(stu.getName()).append(",").append(stu.getAge()).append(",").append(stu.getAddress());
            bw.write(sb.toString());
            bw.newLine(); // 一个学生信息独占一行
            // bw.close();
        }

        bw.close();

    }

上一篇:获取文本上字符出现的次数


下一篇:Java编码