在Java开发中,我们经常需要把TXT里的结构化文本转换成内存中的对象,再对这些对象做统计或排序。假设有一个 student.txt,每行用逗号分隔姓名、年龄和成绩,例如:张三,18,90。下面通过完整示例说明如何读取并排序。

一、定义学生信息类
先创建一个简单的 Student 类,包含姓名、年龄和成绩三个字段,并提供构造方法与 getter。
// 学生类,用于封装TXT中的一行数据
public class Student {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getScore() {
return score;
}
@Override
public String toString() {
return name + "," + age + "," + score;
}
}
二、从TXT读取并解析数据
使用 BufferedReader 按行读取文件,用 split 方法拆分逗号分隔的字段,转为 Student 对象加入 List。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadStudentFile {
public static List<Student> read(String path) throws IOException {
List<Student> list = new ArrayList<>();
// 使用UTF-8编码读取,避免中文乱码
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
continue;
}
String[] parts = line.split(",");
String name = parts[0];
int age = Integer.parseInt(parts[1]);
double score = Double.parseDouble(parts[2]);
list.add(new Student(name, age, score));
}
}
return list;
}
}
三、对学生对象进行排序
利用 Comparator 先按成绩降序,成绩相同再按年龄升序排列。
import java.util.Comparator;
import java.util.List;
public class SortStudent {
public static void sort(List<Student> list) {
list.sort(Comparator.comparing(Student::getScore).reversed()
.thenComparing(Student::getAge));
}
}
四、主程序串联流程
在 main 方法中调用上述方法,完成读取、排序与输出。
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) {
String filePath = "student.txt";
try {
List<Student> students = ReadStudentFile.read(filePath);
SortStudent.sort(students);
for (Student s : students) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
五、注意事项
- TXT文件编码需与 FileReader 默认编码一致,中文环境建议显式使用 InputStreamReader 指定 UTF-8。
- split 后的数组长度要做校验,防止格式错误导致越界。
- 数值转换应捕获 NumberFormatException,提升程序健壮性。
通过上述步骤,我们完成了从文本读取、对象封装到集合排序的完整过程,这是Java处理轻量结构化数据的常用套路。