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.
65 lines
2.4 KiB
65 lines
2.4 KiB
import java.io.*;
|
|
import java.text.SimpleDateFormat;
|
|
import java.util.*;
|
|
|
|
/**
|
|
* 文件工具类:生成文件名、保存题目、读取已有题目
|
|
*/
|
|
public class FileUtils {
|
|
|
|
// 生成文件名
|
|
public static String generateFileName() {
|
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
|
|
return sdf.format(new Date()) + ".txt";
|
|
}
|
|
|
|
// 保存题目到用户文件夹
|
|
public static void saveQuestionsToFile(String userId, String fileName, List<MathQuestion> questions) {
|
|
File userFolder = new File(userId);
|
|
if (!userFolder.exists()) {
|
|
userFolder.mkdirs();
|
|
}
|
|
|
|
File file = new File(userFolder, fileName);
|
|
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
|
|
for (MathQuestion question : questions) {
|
|
writer.write("题号 " + question.getQuestionNumber() + ": " + question.getQuestionText());
|
|
writer.newLine();
|
|
writer.newLine();
|
|
}
|
|
writer.flush();
|
|
} catch (IOException e) {
|
|
throw new RuntimeException("写文件失败: " + file.getAbsolutePath(), e);
|
|
}
|
|
}
|
|
|
|
// 读取用户文件夹下所有 txt 文件中已存在的题目
|
|
public static Set<String> loadExistingQuestions(String userId) {
|
|
Set<String> existingQuestions = new HashSet<>();
|
|
File userFolder = new File(userId);
|
|
if (!userFolder.exists() || !userFolder.isDirectory()) return existingQuestions;
|
|
|
|
File[] files = userFolder.listFiles((dir, name) -> name != null && name.endsWith(".txt"));
|
|
if (files == null) return existingQuestions;
|
|
|
|
for (File f : files) {
|
|
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
|
|
String line;
|
|
while ((line = reader.readLine()) != null) {
|
|
line = line.trim();
|
|
if (line.isEmpty()) continue;
|
|
if (line.startsWith("题号")) {
|
|
int idx = line.indexOf(":");
|
|
if (idx != -1 && idx + 1 < line.length()) {
|
|
existingQuestions.add(line.substring(idx + 1).trim());
|
|
}
|
|
}
|
|
}
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
return existingQuestions;
|
|
}
|
|
}
|