代码实现目标:
将集合中的数据写道文件中通过字符缓冲输出流实现
代码展示
public static void main(String[] args) throws IOException {//创建ArrayList集合ArrayList<Student> array = new ArrayList<>();//创建学生对象Student s1 = new Student("01", "朱文静", "30", "武汉");Student s2 = new Student("02", "zz", "22", "浙江");Student s3 = new Student("03", "ss", "33", "云南");//把学生对象添加到集合中array.add(s1);array.add(s2);array.add(s3);//创建字符缓冲输出流BufferedWriter bw = new BufferedWriter(new FileWriter("student.txt"));//遍历集合,得到每个学生对象for (Student s :array){//把学生对象的数据拼成指定格式的字符串StringBuilder sb = new StringBuilder();sb.append(s.getSid()).append(s.getName()).append(s.getAge()).append(s.getAddress());//调用字符缓冲输出流对象的方法写数据bw.write(sb.toString());bw.newLine();bw.flush();}//释放资源bw.close();}
public class Student {private String sid;private String name;private String age;private String address;public Student(String sid, String name, String age, String address) {this.sid = sid;this.name = name;this.age = age;this.address = address;}public String getSid() {return sid;}public void setSid(String sid) {this.sid = sid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}
}
运行结果