use of cn.hutool.core.io.file.FileReader in project View-Elasticsearch by shencangsheng.
the class QueryTest method main.
public static void main(String[] args) throws Exception {
FileReader templateJson = new FileReader("template.json");
String queryJson = templateJson.readString();
ObjectMapper objectMapper = new ObjectMapper();
List<QueryInstance> queryInstances = objectMapper.readValue(queryJson, new TypeReference<>() {
});
BoolQueryBuilder boolQueryBuilder = BoolQueryBuilderFactory.boolQueryBuilderFactory(queryInstances, new TemplateModuleInstance());
System.out.println(boolQueryBuilder);
}
use of cn.hutool.core.io.file.FileReader in project HOJ by HimitZH.
the class ContestFileController method downloadContestPrintText.
@GetMapping("/download-contest-print-text")
@RequiresAuthentication
@RequiresRoles(value = { "root", "admin", "problem_admin" }, logical = Logical.OR)
public void downloadContestPrintText(@RequestParam("id") Long id, HttpServletResponse response) {
ContestPrint contestPrint = contestPrintService.getById(id);
String filename = contestPrint.getUsername() + "_Contest_Print.txt";
String filePath = Constants.File.CONTEST_TEXT_PRINT_FOLDER.getPath() + File.separator + id + File.separator + filename;
if (!FileUtil.exist(filePath)) {
FileWriter fileWriter = new FileWriter(filePath);
fileWriter.write(contestPrint.getContent());
}
FileReader zipFileReader = new FileReader(filePath);
// 放到缓冲流里面
BufferedInputStream bins = new BufferedInputStream(zipFileReader.getInputStream());
// 获取文件输出IO流
OutputStream outs = null;
BufferedOutputStream bouts = null;
try {
outs = response.getOutputStream();
bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
int bytesRead = 0;
byte[] buffer = new byte[1024 * 10];
// 开始向网络传输文件流
while ((bytesRead = bins.read(buffer, 0, 1024 * 10)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
// 刷新缓存
bouts.flush();
} catch (IOException e) {
log.error("下载比赛打印文本文件异常------------>", e);
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, Object> map = new HashMap<>();
map.put("status", CommonResult.STATUS_ERROR);
map.put("msg", "下载文件失败,请重新尝试!");
map.put("data", null);
try {
response.getWriter().println(JSONUtil.toJsonStr(map));
} catch (IOException ioException) {
ioException.printStackTrace();
}
} finally {
try {
bins.close();
if (outs != null) {
outs.close();
}
if (bouts != null) {
bouts.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
use of cn.hutool.core.io.file.FileReader in project HOJ by HimitZH.
the class TestCaseController method downloadTestcase.
@GetMapping("/download-testcase")
@RequiresAuthentication
@RequiresRoles(value = { "root", "problem_admin" }, logical = Logical.OR)
public void downloadTestcase(@RequestParam("pid") Long pid, HttpServletResponse response) {
String workDir = Constants.File.TESTCASE_BASE_FOLDER.getPath() + File.separator + "problem_" + pid;
File file = new File(workDir);
if (!file.exists()) {
// 本地为空 尝试去数据库查找
QueryWrapper<ProblemCase> problemCaseQueryWrapper = new QueryWrapper<>();
problemCaseQueryWrapper.eq("pid", pid);
List<ProblemCase> problemCaseList = problemCaseService.list(problemCaseQueryWrapper);
Assert.notEmpty(problemCaseList, "对不起,该题目的评测数据为空!");
boolean hasTestCase = true;
if (problemCaseList.get(0).getInput().endsWith(".in") && (problemCaseList.get(0).getOutput().endsWith(".out") || problemCaseList.get(0).getOutput().endsWith(".ans"))) {
hasTestCase = false;
}
Assert.isTrue(hasTestCase, "对不起,该题目的评测数据为空!");
FileUtil.mkdir(workDir);
// 写入本地
for (int i = 0; i < problemCaseList.size(); i++) {
String filePreName = workDir + File.separator + (i + 1);
String inputName = filePreName + ".in";
String outputName = filePreName + ".out";
FileWriter infileWriter = new FileWriter(inputName);
infileWriter.write(problemCaseList.get(i).getInput());
FileWriter outfileWriter = new FileWriter(outputName);
outfileWriter.write(problemCaseList.get(i).getOutput());
}
}
String fileName = "problem_" + pid + "_testcase_" + System.currentTimeMillis() + ".zip";
// 将对应文件夹的文件压缩成zip
ZipUtil.zip(workDir, Constants.File.FILE_DOWNLOAD_TMP_FOLDER.getPath() + File.separator + fileName);
// 将zip变成io流返回给前端
FileReader fileReader = new FileReader(Constants.File.FILE_DOWNLOAD_TMP_FOLDER.getPath() + File.separator + fileName);
// 放到缓冲流里面
BufferedInputStream bins = new BufferedInputStream(fileReader.getInputStream());
// 获取文件输出IO流
OutputStream outs = null;
BufferedOutputStream bouts = null;
try {
outs = response.getOutputStream();
bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
int bytesRead = 0;
byte[] buffer = new byte[1024 * 10];
// 开始向网络传输文件流
while ((bytesRead = bins.read(buffer, 0, 1024 * 10)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();
} catch (IOException e) {
log.error("下载题目测试数据的压缩文件异常------------>{}", e.getMessage());
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, Object> map = new HashMap<>();
map.put("status", CommonResult.STATUS_ERROR);
map.put("msg", "下载文件失败,请重新尝试!");
map.put("data", null);
try {
response.getWriter().println(JSONUtil.toJsonStr(map));
} catch (IOException ioException) {
ioException.printStackTrace();
}
} finally {
try {
bins.close();
if (outs != null) {
outs.close();
}
if (bouts != null) {
bouts.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// 清空临时文件
FileUtil.del(Constants.File.FILE_DOWNLOAD_TMP_FOLDER.getPath() + File.separator + fileName);
}
}
use of cn.hutool.core.io.file.FileReader in project HOJ by HimitZH.
the class ImportQDUOJController method importQDOJProblem.
/**
* @param file
* @MethodName importQDOJProblem
* @Description zip文件导入题目 仅超级管理员可操作
* @Return
* @Since 2021/5/27
*/
@RequiresRoles("root")
@RequiresAuthentication
@ResponseBody
@Transactional(rollbackFor = Exception.class)
@PostMapping("/import-qdoj-problem")
public CommonResult importQDOJProblem(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
if (!"zip".toUpperCase().contains(suffix.toUpperCase())) {
return CommonResult.errorResponse("请上传zip格式的题目文件压缩包!");
}
String fileDirId = IdUtil.simpleUUID();
String fileDir = Constants.File.TESTCASE_TMP_FOLDER.getPath() + File.separator + fileDirId;
String filePath = fileDir + File.separator + file.getOriginalFilename();
// 文件夹不存在就新建
FileUtil.mkdir(fileDir);
try {
file.transferTo(new File(filePath));
} catch (IOException e) {
FileUtil.del(fileDir);
return CommonResult.errorResponse("服务器异常:qduoj题目上传失败!");
}
// 将压缩包压缩到指定文件夹
ZipUtil.unzip(filePath, fileDir);
// 删除zip文件
FileUtil.del(filePath);
// 检查文件是否存在
File testCaseFileList = new File(fileDir);
File[] files = testCaseFileList.listFiles();
if (files == null || files.length == 0) {
FileUtil.del(fileDir);
return CommonResult.errorResponse("评测数据压缩包里文件不能为空!");
}
HashMap<String, File> problemInfo = new HashMap<>();
for (File tmp : files) {
if (tmp.isDirectory()) {
File[] problemAndTestcase = tmp.listFiles();
if (problemAndTestcase == null || problemAndTestcase.length == 0) {
FileUtil.del(fileDir);
return CommonResult.errorResponse("编号为:" + tmp.getName() + "的文件夹为空!");
}
for (File problemFile : problemAndTestcase) {
if (problemFile.isFile()) {
// 检查文件是否时json文件
if (!problemFile.getName().endsWith("json")) {
FileUtil.del(fileDir);
return CommonResult.errorResponse("编号为:" + tmp.getName() + "的文件夹里面的题目数据格式错误,请使用json文件!");
}
problemInfo.put(tmp.getName(), problemFile);
}
}
}
}
// 读取json文件生成对象
HashMap<String, QDOJProblemDto> problemVoMap = new HashMap<>();
for (String key : problemInfo.keySet()) {
try {
FileReader fileReader = new FileReader(problemInfo.get(key));
JSONObject problemJson = JSONUtil.parseObj(fileReader.readString());
QDOJProblemDto qdojProblemDto = QDOJProblemToProblemVo(problemJson);
problemVoMap.put(key, qdojProblemDto);
} catch (Exception e) {
FileUtil.del(fileDir);
return CommonResult.errorResponse("请检查编号为:" + key + "的题目json文件的格式:" + e.getLocalizedMessage());
}
}
QueryWrapper<Language> languageQueryWrapper = new QueryWrapper<>();
languageQueryWrapper.eq("oj", "ME");
List<Language> languageList = languageService.list(languageQueryWrapper);
HashMap<String, Long> languageMap = new HashMap<>();
for (Language language : languageList) {
languageMap.put(language.getName(), language.getId());
}
// 获取当前登录的用户
HttpSession session = request.getSession();
UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo");
List<Tag> tagList = tagService.list(new QueryWrapper<Tag>().eq("oj", "ME"));
HashMap<String, Tag> tagMap = new HashMap<>();
for (Tag tag : tagList) {
tagMap.put(tag.getName().toUpperCase(), tag);
}
List<ProblemDto> problemDtos = new LinkedList<>();
for (String key : problemInfo.keySet()) {
QDOJProblemDto qdojProblemDto = problemVoMap.get(key);
// 格式化题目语言
List<Language> languages = new LinkedList<>();
for (String lang : qdojProblemDto.getLanguages()) {
Long lid = languageMap.getOrDefault(lang, null);
languages.add(new Language().setId(lid).setName(lang));
}
// 格式化标签
List<Tag> tags = new LinkedList<>();
for (String tagStr : qdojProblemDto.getTags()) {
Tag tag = tagMap.getOrDefault(tagStr.toUpperCase(), null);
if (tag == null) {
tags.add(new Tag().setName(tagStr).setOj("ME"));
} else {
tags.add(tag);
}
}
Problem problem = qdojProblemDto.getProblem();
if (problem.getAuthor() == null) {
problem.setAuthor(userRolesVo.getUsername());
}
ProblemDto problemDto = new ProblemDto();
String mode = Constants.JudgeMode.DEFAULT.getMode();
if (qdojProblemDto.getIsSpj()) {
mode = Constants.JudgeMode.SPJ.getMode();
}
problemDto.setJudgeMode(mode).setProblem(problem).setCodeTemplates(qdojProblemDto.getCodeTemplates()).setTags(tags).setLanguages(languages).setUploadTestcaseDir(fileDir + File.separator + key + File.separator + "testcase").setIsUploadTestCase(true).setSamples(qdojProblemDto.getSamples());
problemDtos.add(problemDto);
}
for (ProblemDto problemDto : problemDtos) {
problemService.adminAddProblem(problemDto);
}
return CommonResult.successResponse(null, "导入题目成功");
}
use of cn.hutool.core.io.file.FileReader in project coding-more by itwanger.
the class Convert method main.
public static void main(String[] args) throws IOException {
FileReader fileReader = FileReader.create(new File(docPath + fileName), Charset.forName("utf-8"));
List<String> list = fileReader.readLines();
FileWriter writer = new FileWriter(docPath + fileName);
int num = 1;
for (String line : list) {
Matcher m = pattern.matcher(line);
if (m.matches()) {
// 处理图片
// png 还是 gif 还是 jpg
String imgSuffixTemp = pngSuffix;
int index = line.indexOf(pngSuffix);
if (index == -1) {
index = line.indexOf(gifSuffix);
imgSuffixTemp = gifSuffix;
if (index == -1) {
index = line.indexOf(jpgSuffix);
imgSuffixTemp = jpgSuffix;
if (index == -1) {
index = line.indexOf(jpegSuffix);
imgSuffixTemp = jpegSuffix;
}
}
}
if (index == -1) {
writer.append(line + "\n");
} else {
System.out.println("处理图片" + line);
String originImgUrl = line.substring("![](".length(), index) + imgSuffixTemp;
String destinationImgPath = imgPath + key + "-" + num + imgSuffixTemp;
// 1、下载到本地
new Thread(new MyRunnable(originImgUrl, destinationImgPath)).start();
// 2、修改 MD 文档
writer.append("![](" + imgCdnPre + num + imgSuffixTemp + ")\n");
num++;
}
} else {
writer.append(line + "\n");
}
}
writer.flush();
}
Aggregations