假如现在给你一个txt文件,该文件中存在学生基本信息,如:学生名称、性别和年龄。每行存放一个学生信息,每个元信息之间是有空格分割。然后将这些学生信息通过IO解析出来并且按照年龄从大到小进行排序,最后输出学生信息。
txt文件的内容(studentData.txt):
# 姓名 性别 年龄(使用空格分割) 张三 男 23 李四 男 25 王怡 女 27 赵燕 女 21
实现思路:
使用BufferedReader解析给定的txt文件,每次读取一行,然后将学生信息按照空格分解出来设置到Student对象,且将这个Student添加到List中,最后使用Collections的sort方法来排序。
实现代码:
package com.bug315.application; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class StudentInfo { private List<Student> studentList; public static void main(String[] args) { StudentInfo studentInfo = new StudentInfo(); studentInfo.readStudentInfo("document/studentData.txt"); studentInfo.comparator(); studentInfo.print(); } public void print() { for (Student stu : studentList) { System.out.println(stu); } } public void comparator() { Collections.sort(this.studentList, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getAge().compareTo(o2.getAge()); } }); // 翻转List Collections.reverse( this.studentList ); } public void readStudentInfo(String filePath) { studentList = new ArrayList<Student>(); BufferedReader reader = null; try { reader = new BufferedReader( new InputStreamReader(new FileInputStream(filePath)) ); String line = ""; while ( (line = reader.readLine()) != null ) { // #表示注释行 if ( !line.startsWith("#") ) { String[] strs = line.split("\s+"); if ( strs.length == 3 ) { Student stu = new Student(); stu.setName( strs[0] ); stu.setSex( strs[1] ); try { stu.setAge( new Integer(strs[2]) ); } catch(NumberFormatException number) { stu.setAge( new Integer("0") ); } studentList.add(stu); } else { throw new RuntimeException("存在不正确的数据行"); } } } } catch( Exception e ) { e.printStackTrace(); } finally { if ( null != reader) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } // } } class Student { // 用户名 private String name; // 性别 private String sex; // 年龄 private Integer age; 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; } @Override public String toString() { return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]"; } }
运行结果:
Student [name=王怡, sex=女, age=27] Student [name=李四, sex=男, age=25] Student [name=张三, sex=男, age=23] Student [name=赵燕, sex=女, age=21]