public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
import java.util.*;
import java.io.*;public class Job2Main {
static final String studentsFileName = "Student.txt";
/*
* 将List中的Student保存到Student.txt文件中
* 格式:
* 一个Student一行,行的格式如下
* 学号,姓名,年龄
* Student.txt示例
* 1,zhang3,20
* 2,Li4,20
* 3,Wang5,20
*/
void saveStudent(List<Student> students) {
//请完成此方法
}
/*
* 读取Student.txt文件中的学生数据,每一行创建一个Student的对象,
* 多行数据便可以创建多个Student的对象,将这些对象保存到List中
* Student.txt示例
* 1,zhang3,20
* 2,Li4,20
* 3,Wang5,20
*/
List<Student> loadStudent() {
List<Student> stuList = new ArrayList<Student>();
//完成些方法
return stuList;
} public static void main(String[] args) {
Job2Main job2=new Job2Main();
Student s1=new Student(1, "zhang3", 20);
Student s2=new Student(2, "Li4", 20);
Student s3=new Student(3, "Wang5", 20);
List<Student> stuList=new ArrayList<Student>();
stuList.add(s1);
stuList.add(s2);
stuList.add(s3);
job2.saveStudent(stuList);
List<Student> students=job2.loadStudent();
for(Student s:students){
System.out.println(s);
}
}}
运行结果
控制台输出
Student [id=1, name=zhang3, age=20]
Student [id=2, name=Li4, age=20]
Student [id=3, name=Wang5, age=20]
生成的Student.txt文件
1,zhang3,20
2,Li4,20
3,Wang5,20
小弟在此感谢。
不懂的地方可以来问,这个需要通过你自己的学习来完成.
FileWriter writer = new FileWriter("F:\\Student.txt");
BufferedWriter bw=new BufferedWriter (writer );
for (Student s : stuList) {
// 将s中数据拼字符串,然后用bw.write输出,再换行..读取就是这个过程的逆向.
}
bw.flush();
bw.close();
writer.close();
/** 把学生信息保存到文件 **/
public void saveStudents() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(students);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("保存失败");
} finally {
if (oos != null) {
try {
oos.close();
} catch (Exception e2) {
}
}
}
} /** 从文件读取学生信息 **/
public void readStudents() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(fileName));
students = (Set<Student>) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("读取失败");
} finally {
if (ois != null) {
try {
ois.close();
} catch (Exception e2) {
}
}
}
}