【修改】 C语言因为电脑编码读取不到文件内容

This commit is contained in:
dlaren
2025-07-16 09:27:53 +08:00
parent eb971b8c26
commit 7d796b123c
6 changed files with 48 additions and 20 deletions

View File

@@ -73,7 +73,7 @@ public class AutoController {
* @return 判分结果 * @return 判分结果
*/ */
@PostMapping("/judgementForC") @PostMapping("/judgementForC")
public Result<BigDecimal> judgementForC(@RequestBody StuInfoVo stuInfoVo){ public Result<BigDecimal> judgementForC(@RequestBody StuInfoVo stuInfoVo) throws IOException {
return Result.success(autoService.autoForC(stuInfoVo)); return Result.success(autoService.autoForC(stuInfoVo));
} }
// WPS-WORD // WPS-WORD

View File

@@ -2,6 +2,7 @@ package com.example.exam.exam.service.autoforc;
import com.example.exam.exam.controller.auto.vo.StuInfoVo; import com.example.exam.exam.controller.auto.vo.StuInfoVo;
import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
/** /**
@@ -13,5 +14,5 @@ public interface AutoForCService {
* 自动判题 C语言 * 自动判题 C语言
* @param stuInfoVo 学生信息 * @param stuInfoVo 学生信息
*/ */
BigDecimal autoForC(StuInfoVo stuInfoVo); BigDecimal autoForC(StuInfoVo stuInfoVo) throws IOException;
} }

View File

@@ -12,6 +12,7 @@ import jakarta.annotation.Resource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@@ -37,7 +38,7 @@ public class AutoForCServiceImpl implements AutoForCService {
* @return 是否通过 * @return 是否通过
*/ */
@Override @Override
public BigDecimal autoForC(StuInfoVo stuInfoVo) { public BigDecimal autoForC(StuInfoVo stuInfoVo) throws IOException {
SystemTenant systemTenant = systemTenantService.getId(stuInfoVo.getSchoolName()); SystemTenant systemTenant = systemTenantService.getId(stuInfoVo.getSchoolName());
BigDecimal score = new BigDecimal(0); BigDecimal score = new BigDecimal(0);
// 0、获取到试卷信息试卷详情 // 0、获取到试卷信息试卷详情
@@ -67,10 +68,11 @@ public class AutoForCServiceImpl implements AutoForCService {
EducationPaperQu educationPaperQu = results.get(); EducationPaperQu educationPaperQu = results.get();
String quScore = educationPaperScheme.getQuScores(); String quScore = educationPaperScheme.getQuScores();
ExamQuestion examQuestion = examQuestionService.selectExamQuestionByQuId(quId); ExamQuestion examQuestion = examQuestionService.selectExamQuestionByQuId(quId);
System.out.println(wjFile);
File[] lastFiles = wjFile.listFiles(); File[] lastFiles = wjFile.listFiles();
for (File lastFile : lastFiles) { for (File lastFile : lastFiles) {
System.out.println(lastFile);
if (lastFile.getName().contains(".c")) { if (lastFile.getName().contains(".c")) {
System.out.println("开始C语言判分"+quNumber);
String judgementStr = "<p>-----------------------------------------------------------</p>"; String judgementStr = "<p>-----------------------------------------------------------</p>";
judgementStr += "<p>试题序号:" + educationPaperQu.getSort() + "</p>"; judgementStr += "<p>试题序号:" + educationPaperQu.getSort() + "</p>";
judgementStr += "<p>试题编号:" + examQuestion.getQuNum() + "</p>"; judgementStr += "<p>试题编号:" + examQuestion.getQuNum() + "</p>";

View File

@@ -4,6 +4,8 @@ package com.example.exam.exam.service.c;
import com.example.exam.exam.dal.ExamQuestion; import com.example.exam.exam.dal.ExamQuestion;
import com.example.exam.exam.dal.SourceAndText; import com.example.exam.exam.dal.SourceAndText;
import java.io.IOException;
/** /**
* 判分逻辑集合 * 判分逻辑集合
* *
@@ -19,7 +21,7 @@ public interface JudgementService {
* @param score 分数 * @param score 分数
* @return 返回判分 * @return 返回判分
*/ */
public SourceAndText ProgrammingC(double score, String pathC, String fileName, ExamQuestion examQuestion, String judgementStr); public SourceAndText ProgrammingC(double score, String pathC, String fileName, ExamQuestion examQuestion, String judgementStr) throws IOException;
} }

View File

@@ -9,6 +9,7 @@ import com.example.exam.exam.utils.c.LogFileUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.example.exam.exam.dal.SourceAndText; import com.example.exam.exam.dal.SourceAndText;
import java.io.IOException;
import java.util.*; import java.util.*;
/** /**
@@ -28,7 +29,7 @@ public class JudgementServiceImpl implements JudgementService
* @return 返回判分 * @return 返回判分
*/ */
@Override @Override
public SourceAndText ProgrammingC(double score, String pathC, String fileName, ExamQuestion examQuestion, String judgementStr) { public SourceAndText ProgrammingC(double score, String pathC, String fileName, ExamQuestion examQuestion, String judgementStr) throws IOException {
SourceAndText sourceAndText = new SourceAndText(); SourceAndText sourceAndText = new SourceAndText();
// 关键字比对,超过权重-测试用例/运行(测试用例全对,直接满分-不全对)-结果,不超过权重只给关键字几个的分 // 关键字比对,超过权重-测试用例/运行(测试用例全对,直接满分-不全对)-结果,不超过权重只给关键字几个的分
// 获取该题有多少分 // 获取该题有多少分
@@ -66,6 +67,7 @@ public class JudgementServiceImpl implements JudgementService
// 创建log文件txt用于记录 // 创建log文件txt用于记录
// LogFileUtils.createFile(pathC + "/log.txt"); // LogFileUtils.createFile(pathC + "/log.txt");
System.out.println(pathC + " --- " + fileName);
String code = JudgementCUtils.readFile(pathC, fileName); String code = JudgementCUtils.readFile(pathC, fileName);
// LogFileUtils.writeLine("✅ 系统开始读取学生考试文件:" + code); // LogFileUtils.writeLine("✅ 系统开始读取学生考试文件:" + code);
judgementStr = HtmlAppender.appendHtmlLine(judgementStr, "✅ 系统开始读取学生考试文件:" + code); judgementStr = HtmlAppender.appendHtmlLine(judgementStr, "✅ 系统开始读取学生考试文件:" + code);

View File

@@ -2,7 +2,10 @@ package com.example.exam.exam.utils.c;
import javax.swing.*; import javax.swing.*;
import java.io.*; import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.charset.UnmappableCharacterException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
@@ -190,35 +193,53 @@ public class JudgementCUtils
* @param filePath 文件路径 * @param filePath 文件路径
* @return 文件内容 * @return 文件内容
*/ */
public static String readFile(String filePath, String fileName) { public static String readFile(String filePath, String fileName) throws IOException {
// 创建一个 Path 对象,指向包含 C 语言文件的文件夹 Path folderPath = Paths.get(filePath).normalize().toAbsolutePath();
Path folderPath = Paths.get(filePath);
// 判断路径是否存在
if (!Files.exists(folderPath)) { if (!Files.exists(folderPath)) {
return null; // 或者 return null或者 throw new RuntimeException(...),看你的函数定义 throw new FileNotFoundException("路径不存在: " + folderPath);
} }
// 使用 StringBuilder 来累积所有读取到的代码内容
StringBuilder codeBuilder = new StringBuilder(); StringBuilder codeBuilder = new StringBuilder();
final boolean[] fileFound = {false};
try (Stream<Path> paths = Files.walk(folderPath)) { try (Stream<Path> paths = Files.walk(folderPath)) {
paths.filter(Files::isRegularFile) paths.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().equalsIgnoreCase(fileName)) .filter(path -> path.getFileName().toString().equals(fileName)) // 精确匹配
.forEach(path -> { .forEach(path -> {
fileFound[0] = true;
try { try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); Charset charset = detectCharset(path);
for (String line : lines) { List<String> lines = Files.readAllLines(path, charset);
codeBuilder.append("\n").append(line); lines.forEach(line -> {
codeBuilder.append(line).append("\n");
System.out.println(" " + line); System.out.println(" " + line);
} });
} catch (IOException e) { } catch (IOException e) {
// LogFileUtils.writeLine("❗ 无法读取文件: " + path); throw new UncheckedIOException("无法读取文件: " + path, e);
} }
}); });
} catch (IOException e) {
return null;
} }
if (!fileFound[0]) {
throw new FileNotFoundException("未找到文件: " + fileName + " 在路径: " + folderPath);
}
return codeBuilder.toString(); return codeBuilder.toString();
} }
private static Charset detectCharset(Path path) throws IOException {
// 常见中文编码列表
Charset[] candidates = {StandardCharsets.UTF_8, Charset.forName("GBK"),
StandardCharsets.ISO_8859_1, StandardCharsets.UTF_16};
for (Charset charset : candidates) {
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
reader.read();
return charset; // 如果能正常读取第一个字符,可能是正确编码
} catch (MalformedInputException | UnmappableCharacterException e) {
// 尝试下一个编码
}
}
return StandardCharsets.UTF_8; // 默认回退
}
} }