一个文本文件中包含若干行name,sex,age,address数据,
每个数据间以逗号分割。编写方法读取文本文件将数据保存成List集合。
List中的元素类型自定义为Student。方法参数是要读取的文件的File对象和转换成的类类型。
要求使用这种方法,下面我的代码直接用的Student类作为返回参数泛型
public <T> List<T> saveFile(File file,Class<T> c){}
public class GenericInterface {
public static void main(String[] args) {
File f = new File("d.txt");
List<Student> list = saveFile(f);
for(Student s:list) {
System.out.println(s);
}
}
private static List<Student> saveFile(File file){
List<Student> list = new ArrayList<>();
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String s = "";
while((s = in.readLine())!=null) {
String str[] = s.split(",");
list.add(new Student(str[0], str[1], Integer.valueOf(str[2]), str[3]));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}
class Student{
private String name;
private String sex;
private Integer age;
private String address;
public Student() {
super();
}
public Student(String name, String sex, Integer age, String address) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + ", age=" + age + ", address=" + address + "]";
}
}