package cn.itcawt.Demo;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class Demo06 {
public static void main(String[] args) throws IOException {
//定义学生类
//创建ArrayList集合对象
ArrayList<Student> arr = new ArrayList<>();
//创建学生对象
Student s1 = new Student("itheima001", "周杰伦", 40, "台北");
Student s2 = new Student("itheima002", "薛之谦", 35, "上海");
Student s3 = new Student("itheima003", "林宥嘉", 32, "屏东");
Student s4 = new Student("itheima004", "杨宗纬", 41, "桃园");
//把学生对象添加到集合中
arr.add(s1);
arr.add(s2);
arr.add(s3);
arr.add(s4);
//创建字符缓冲输出流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("Honey\\Sing.txt"));
//遍历集合,得到每一个学生对象
for (Student s : arr) {
//把学生对象的数据拼接成指定格式的字符串
StringBuilder sb = new StringBuilder();
sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
//调用字符缓冲输出流的方法写数据
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
//释放资源
bw.close();
}
} |
|