package persistence; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class QuestionChecker { public static boolean isDuplicate(String username, String question) { File dir = new File(username); if (!dir.exists()) return false; File[] files = dir.listFiles();/*每次调用都获取一次文件列表*/ if (files == null) return false; // 待查题目去掉空格,方便精确匹配 String target = question.trim(); for (File file : files) {/* 遍历所有历史文件 */ if (file.isFile() && file.getName().endsWith(".txt")) { try (Scanner scanner = new Scanner(file)) { while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); /*遍历文件中的每一行 */ if (line.isEmpty()) continue;// 跳过空行 // 去掉题号部分(如 "1. ") int dotIndex = line.indexOf('.'); if (dotIndex != -1) { String storedQuestion = line.substring(dotIndex + 1).trim(); // 精确匹配 if (storedQuestion.equals(target)) { return true; } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } } return false; } }