題目: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為姓名