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.
partner_project/src/util/FileUtils.java

80 lines
2.6 KiB

package util;
import generator.Problem;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class FileUtils {
private static final String FOLDER_PATH = "exams/";
public static String getUserFolder(String username) {
String folder = FOLDER_PATH + username;
File dir = new File(folder);
if (!dir.exists()) {
dir.mkdirs();
}
return folder;
}
private static void processHistoryFile(File file, Set<String> history) {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
if (!line.trim().isEmpty() && line.matches("^\\d+\\..*")) {
// 仅提取题干 (表达式字符串) 用于查重
history.add(line.substring(line.indexOf('.') + 1).trim());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static Set<String> loadHistory(String username) {
Set<String> history = new HashSet<>();
File dir = new File(getUserFolder(username));
File[] files = dir.listFiles((d, name) -> name.endsWith(".txt"));
if (files != null) {
for (File file : files) {
processHistoryFile(file, history);
}
}
return history;
}
private static void writeProblem(BufferedWriter bw, int index, Problem problem) throws IOException {
bw.write(index + "." + problem.getExpression());
bw.newLine();
char optionChar = 'A';
StringBuilder optionsLine = new StringBuilder();
for (String option : problem.getOptions()) {
optionsLine.append(optionChar++).append(". ").append(option).append(" ");
}
bw.write(optionsLine.toString().trim());
bw.newLine();
bw.write("答案: " + problem.getCorrectAnswerOption());
bw.newLine();
bw.newLine();
}
public static void saveProblems(String username, List<Problem> problems) {
String folder = getUserFolder(username);
String timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
String filename = folder + "/" + timestamp + ".txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
int index = 1;
for (Problem problem : problems) {
writeProblem(bw, index++, problem);
}
System.out.println("卷子已保存到: " + filename);
} catch (IOException e) {
e.printStackTrace();
}
}
}