代码主要是将文本文件中的数据写到集合中,运用到的是java字节缓冲输入流的知识点。
public static void main(String[] args) throws IOException {
//创建字符缓冲流输入对象
BufferedReader bufferedReader = new BufferedReader(new FileReader("student.txt"));
//创建ArrayList集合对象
ArrayList<Student> array = new ArrayList<>();
//调用字符缓冲输入流对象的方法读数据
String line;
while((line=bufferedReader.readLine())!=null){
//把读到的数据用split()进行分割,得到一个字符串数组
String[] strArray = line.split(",");
//创建学生对象
Student s = new Student();
//把字符串数组中每一个元素取出来对应的赋值给学生对象的成员变量值
s.setSid(strArray[0]);
s.setName(strArray[1]);
s.setAge(strArray[2]);
s.setAddress(strArray[3]);
//把学生对象添加到集合中
array.add(s);
}
//释放资源
bufferedReader.close();
//遍历集合
for (Student s:array){
System.out.println(s);
}
}
public class Student {
private String sid;
private String name;
private String age;
private String address;
public Student() {
}
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;
}
@Override
public String toString() {
return "Student{" +
"sid='" + sid + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
", address='" + address + '\'' +
'}';
}
}
文本中的内容
运行结果