✅ 功能说明
- 从文件读取
riders.txt(格式:姓名,里程) - 排序并输出降序排行榜
- 支持异常处理 & 空文件提示
- 全程无第三方依赖,JDK 8+ 直接跑
📄 riders.txt 示例(放在项目根目录)
Alice,120.5
Bob,88.0
Charlie,105.2
David,134.8
🚀 Java源码:Main.java
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String fileName = "riders.txt";
try {
List<Rider> riders = loadRiders(fileName);
if (riders.isEmpty()) {
System.out.println("文件为空,暂无骑行数据!");
return;
}
// 降序排序
riders.sort((r1, r2) -> Double.compare(r2.distance, r1.distance));
// 打印排行榜
System.out.println("🏆 骑行里程排行榜 🏆");
for (int i = 0; i < riders.size(); i++) {
System.out.printf("第%2d名:%-8s %.1f km%n", i + 1, riders.get(i).name, riders.get(i).distance);
}
} catch (IOException e) {
System.err.println("读取文件失败:" + e.getMessage());
}
}
/* 读取并解析文件 */
private static List<Rider> loadRiders(String fileName) throws IOException {
return Files.lines(Paths.get(fileName))
.filter(line -> !line.trim().isEmpty())
.map(line -> {
String[] parts = line.split(",");
if (parts.length != 2) return null;
try {
double dist = Double.parseDouble(parts[1].trim());
return new Rider(parts[0].trim(), dist);
} catch (NumberFormatException e) {
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
/* 内部实体类 */
private static class Rider {
final String name;
final double distance;
Rider(String name, double distance) {
this.name = name;
this.distance = distance;
}
}
}
✅ 运行效果
🏆 骑行里程排行榜 🏆
第 1名:David 134.8 km
第 2名:Alice 120.5 km
第 3名:Charlie 105.2 km
第 4名:Bob 88.0 km
🏁 一句话总结
“文件进来,Stream 处理,Lambda 排序,排行榜秒出!”
无框架、无依赖,JDK 自带类搞定一切!🛠️