Java笔试题-C盘下面有一个aa.txt的文件,文件里存放了年级每一个学生的成绩看,格式为:姓名 分数 班级

题目:C盘下面有一个aa.txt的文件,文件里存放了年级每一个学生的成绩看,格式为:姓名 分数 班级如:

张三80 1班

李四90 2班

设计一个方法,读取文件里的信息,最后输出学生的信息,输出格式为:姓名:张三 分数:80 班级:1班

要求:使用类存储每一行学生信息,使用list存储所有的学生信息。

public class ReadTextLine {
public static void main(String[] args) throws IOException {
    List<Student> list=getReader("E:\\score.txt");
    System.out.println(list);
    for(Student s:list){
        System.out.println("姓名:"+s.getName()+" "+"分数:"+s.getScore()+"班级:"+s.getCls());
    }
}
public static List<Student> getReader(String path) throws IOException{
     List<Student> students=new ArrayList<Student>();
    FileInputStream in=new FileInputStream(new File(path));
    InputStreamReader inr=new InputStreamReader(in);
    BufferedReader buf=new BufferedReader(inr);
    String s="";
    while((s=buf.readLine())!=null){
        Student student=new Student();
        int index=s.indexOf(" ");
        student.setName(s.substring(0,index-2));
        student.setScore(Integer.parseInt(s.substring(index-2,index)));
        student.setCls(s.substring(index,s.length()));
        students.add(student);
    }
    in.close();
    buf.close();
    inr.close();
    return students;
}
}

存储类:

public class Student {
    private String name;
    private int score;
    private String cls;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getCls() {
        return cls;
    }

    public void setCls(String cls) {
        this.cls = cls;
    }

}

利用IO流读取文件信息:file-->FileInputStream-->InputStreamReader-->BufferedReader在通过while循环将每一行数据取出,每一次取出将其放入一个临时的String中,当为null时停止

将每一行数据通过空格分隔,空格以后的为班级,空格前两个为成绩,2位数,0到空格-2为姓名

猜你喜欢

转载自www.cnblogs.com/ys15/p/11525449.html