You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.7 KiB
75 lines
2.7 KiB
import java.io.*;
|
|
import java.nio.file.*;
|
|
|
|
/**
|
|
* 课堂练习:重构"裸奔"代码
|
|
* 使用 try-with-resources 确保流自动关闭,处理三类异常
|
|
*/
|
|
public class ScoreReader {
|
|
|
|
public static void main(String[] args) {
|
|
// 创建一个测试用的 scores.txt(实际场景中文件已存在)
|
|
createSampleFile();
|
|
|
|
System.out.println("=== 正常读取 ===");
|
|
readAndPrintAverage("scores.txt");
|
|
|
|
System.out.println("\n=== 文件不存在 ===");
|
|
readAndPrintAverage("notfound.txt");
|
|
|
|
System.out.println("\n=== 含非数字行 ===");
|
|
createBadFile();
|
|
readAndPrintAverage("bad_scores.txt");
|
|
}
|
|
|
|
/**
|
|
* 重构后的核心方法:
|
|
* 1. try-with-resources 自动关闭流(无需手动 br.close())
|
|
* 2. 分层处理三类异常:文件不存在 / 读取错误 / 数字格式错误
|
|
*/
|
|
public static void readAndPrintAverage(String filename) {
|
|
int sum = 0;
|
|
int count = 0;
|
|
|
|
// try-with-resources:括号内声明的资源在 try 结束后自动关闭
|
|
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
|
|
String line;
|
|
while ((line = br.readLine()) != null) {
|
|
line = line.trim();
|
|
if (line.isEmpty()) continue; // 跳过空行
|
|
try {
|
|
sum += Integer.parseInt(line); // 可能抛 NumberFormatException
|
|
count++;
|
|
} catch (NumberFormatException e) {
|
|
System.out.println(" 警告:跳过非数字行 [" + line + "]");
|
|
}
|
|
}
|
|
} catch (FileNotFoundException e) {
|
|
System.out.println(" 错误:文件不存在 -> " + filename);
|
|
return;
|
|
} catch (IOException e) {
|
|
System.out.println(" 错误:文件读取失败 -> " + e.getMessage());
|
|
return;
|
|
}
|
|
|
|
if (count == 0) {
|
|
System.out.println(" 无有效成绩数据。");
|
|
} else {
|
|
System.out.printf(" 共 %d 条成绩,平均分:%.2f%n", count, (double) sum / count);
|
|
}
|
|
}
|
|
|
|
// ── 辅助:生成测试文件 ──
|
|
private static void createSampleFile() {
|
|
try (PrintWriter pw = new PrintWriter("scores.txt")) {
|
|
pw.println("85"); pw.println("92");
|
|
pw.println("78"); pw.println("90"); pw.println("88");
|
|
} catch (IOException ignored) {}
|
|
}
|
|
|
|
private static void createBadFile() {
|
|
try (PrintWriter pw = new PrintWriter("bad_scores.txt")) {
|
|
pw.println("75"); pw.println("abc"); pw.println("88");
|
|
} catch (IOException ignored) {}
|
|
}
|
|
}
|
|
|