题目:读取C盘的a.txt文档,把文档中的内容解析为数据1封装在学生信息中。
Student类
package KeTangText.FileAndStringZH;
import java.util.Date;
public class Student {
private String name;
private String sex;
private Date brithday;
private String address;
public Student(){
}
public Student(String name,String sex,Date brithday,String address) {
this.name=name;
this.sex=sex;
this.brithday=brithday;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setBrithday(Date brithday) {
this.brithday = brithday;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", brithday=" + brithday +
", address='" + address + '\'' +
'}';
}
}
ZongHeTest类
package KeTangText.FileAndStringZH;
import KeTangText.FileAndStringZH.Student;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
public class ZongHeTest {
public static void main(String[] args) throws IOException, ParseException {
//1.定义File对象,关联映射磁盘文件
File f1=new File("c:/a.txt");
//定义缓冲字符流
FileReader fr=new FileReader(f1);
BufferedReader br=new BufferedReader(fr);
//对文档进行读取每次读取一行数据
ArrayList<Student> list=new ArrayList<>();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
String temp;
while (true){
temp= br.readLine();//读取一行数据
if (temp!=null){
System.out.println(temp);//张三-男-2000/08/15-河南南阳
String[] splist=temp.split("-");//把字符串按照-解析出来4个数据存入数组中,[张三, 男, 2000/08/15, 河南南阳]
System.out.println(Arrays.toString(splist));
//每一行内容对应的数组元素取出来封装到Student对象中
Student student=new Student();
student.setName(splist[0]);
student.setSex(splist[1]);
student.setBrithday(sdf.parse(splist[2]));//去除数组中第三个元素,是一个日期字符串,把他转换为对应的日期
student.setAddress(splist[3]);
list.add(student);
}else{
break;
}
}
System.out.println(list);
}
}