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.
43 lines
1.3 KiB
43 lines
1.3 KiB
package mathpuzzle.service;
|
|
|
|
import mathpuzzle.entity.User;
|
|
import java.io.BufferedWriter;
|
|
import java.io.FileWriter;
|
|
import java.io.IOException;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.Paths;
|
|
import java.time.LocalDateTime;
|
|
import java.time.format.DateTimeFormatter;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* 文件处理器 负责创建用户目录和保存试卷文件
|
|
*/
|
|
public class FileHandler {
|
|
|
|
public void ensureUserDirectory(User user) throws IOException {
|
|
String dirPath = "./" + user.getName();
|
|
Path path = Paths.get(dirPath);
|
|
if (!Files.exists(path)) {
|
|
Files.createDirectories(path);
|
|
}
|
|
}
|
|
|
|
public void savePaper(User user, List<String> questions) throws IOException {
|
|
ensureUserDirectory(user);
|
|
// 生成文件名:年-月-日-时-分-秒.txt
|
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
|
|
String fileName = LocalDateTime.now().format(formatter) + ".txt";
|
|
String filePath = "./" + user.getName() + "/" + fileName;
|
|
|
|
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
|
|
for (int i = 0; i < questions.size(); i++) {
|
|
writer.write((i + 1) + ". " + questions.get(i)); // 添加题号
|
|
writer.newLine();
|
|
writer.newLine(); // 每题之间空一行
|
|
}
|
|
}
|
|
}
|
|
}
|