把学生对象添加到集合里面去 再把集合里面的数据一行一行的放到文件里面去
学生类代码:
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;
}
@Override
public String toString() {
String data ;
data = id+","+name+","+Integer.toString(age)+","+address;
return data;
}
main方法
public static void main(String[] args) throws IOException {
//创建学生对象
Student s1 = new Student("001","海洋",22,"河南");
Student s2 = new Student("002","大涛",23,"安徽");
Student s3 = new Student("003","明明",24,"北京");
Student s4 = new Student("004","飒飒",27,"上海");
//创建集合
ArrayList<Student> array = new ArrayList<>();
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
//字符输出流
FileWriter fw = new FileWriter("C:\\Users\\Administrator\\IdeaProjects\\Day07\\a.txt");
//自符缓冲流对象
BufferedWriter bw = new BufferedWriter(fw);
//开始写数据
for (Student student : array){
//写数据
bw.write(student.toString());
//换行
bw.newLine();
//刷新
bw.flush();
}
//释放资源
bw.close();
}
效果