案例:集合到文件(改进版)
1.需求: 把ArrayList集合中的学生数据写入到文本文件。要求:每一个学生对象的数据作为文件中的一行数据
格式:学号,姓名,年龄,居住地
2.思路:
- 定义学生类
- 创建ArrayList集合
- 创建学生对象
- 把学生对象添加到集合中
- 创建字符缓冲输出流对象
- 遍历集合,得到每一个学生对象
- 把学生对象的数据拼接成指定格式的字符串
- 调用字符串输出流对象的方法写数据
- 释放资源
学生类:
package com.characterstream.example01;
public class Student {
private String id;
private String name;
private int age;
private String address;
public Student() {
}
public Student(String id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
测试类:
package com.characterstream.example01;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class ArrayListToFileDemo {
public static void main(String[] args) throws IOException {
//创建ArrayList集合
ArrayList<Student> array = new ArrayList<>();
//创建学生对象
Student s1 = new Student("001","郝佳乐",20,"西安");
Student s2 = new Student("002","张曼玉",35,"武汉");
Student s3 = new Student("003","王祖贤",33,"郑州");
//把学生对象添加到集合中
array.add(s1);
array.add(s2);
array.add(s3);
//创建字符缓冲输出流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("基础语法\\students.txt"));
//遍历集合得到每一个学生对象
for(Student s:array){
//把学生对象的数据拼接成指定字符串的数据
StringBuilder sb = new StringBuilder(); sb.append(s.getId()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
//调用方法写数据
//将StringBuilder转换为String
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close();
}
}