简单的文件操作
1. 需求
- 文件生成获取删除案例
想在项目跟目录生成一个文件,然后对文件进行操作,要在window
以及linux
服务都可以进行操作,这时候需要使用System.getProperty("user.dir")
获取项目根目录,方便项目进行文件操作 - 文件存储数据以及读取
项目中有bpmn流程文件,需要进行记录解析与存储,当前存储到数据库,后续还要给前端进行使用。
2. 文件生成获取删除案例
整体代码部分相对简单,主要包含文件创建,文件内容获取,文件删除,以及获取resource目录下文件内容
项目整体结构如下图
2.1 controller主要代码实现
package cn.git.controller;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* @description: 文件路径测试
* @program: bank-credit-sy
* @author: lixuchun
* @create: 2023-08-08
*/
@RestController
@RequestMapping("/path")
public class PathTestController {
/**
* 生成一个文件到resource目录下
*
* @return
*/
@GetMapping("/makeFile")
public String makeFile() {
// 在服务根目录创建一个文件
String bathPath = System.getProperty("user.dir").concat(StrUtil.SLASH).concat("test.txt");
File file = new File(bathPath);
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("123");
fileWriter.flush();
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
/**
* 读取文件内容
*
* @return
* @throws IOException
*/
@GetMapping("/getFile")
public String getFile() throws IOException {
String bathPath = System.getProperty("user.dir").concat(StrUtil.SLASH).concat("test.txt");
File file = new File(bathPath);
// 读取txt内容信息
FileReader fileReader = new FileReader(file);
char[] chars = new char[1024];
int len = fileReader.read(chars);
fileReader.close();
return new String(chars, 0, len);
}
/**
* 删除文件
*
* @return
*/
@GetMapping("/dropFile")
public String dropFile() {
String bathPath = System.getProperty("user.dir").concat(StrUtil.SLASH).concat("test.txt");
File file = new File(bathPath);
if (file.exists()) {
file.delete();
}
return "删除成功";
}
/**
* 读取resource目录下的文件
*
* @return
* @throws IOException
*/
@GetMapping("/getResourceFile")
public String getResourceFile() throws IOException {
// 通过classLoader获取inputStream
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("name.txt");
StringBuilder content = new StringBuilder();
try {
assert inputStream != null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
2.2 测试
上传jar包,并且java -jar
简单启动服务
生成文件
获取文件内容
查看生成文件以及文件内容
获取resource目录下文件信息
3. 文件存储数据以及读取
此处使用原有DragRule拖拽规则部分简化实现代码,不进行测试了,具体代码如下
-
文件上传数据库
/** * 添加链信息 * * @param dragRuleChain 规则链 * @param uri * @param file */ @Override public void addChain(String dragRuleChain, String uri, MultipartFile file) throws IOException { // 文件名称,以及base64编码字符串 String fileName = file.getOriginalFilename(); String fileBase64Str = Base64.getEncoder().encodeToString(file.getBytes()); // 获取缓存信息,作为最终返回参数 Object dragRuleChainObj = redisUtil.hget(CommonDragRuleConstant.DRAG_RULE_CHAIN_FLAG, uri); if (ObjectUtil.isNull(dragRuleChainObj)) { throw new ServiceException(StrUtil.format("当前缓存中没有uri[{}]规则链信息,请确认是否缓存中没有数据!", uri)); } DragChainDTO cacheDragChainDTO = JSONObject.parseObject(dragRuleChainObj.toString(), DragChainDTO.class); // 校验当前规则链参数是否合法,满足所有规则入参出参 commonDragRuleUtil.checkDragRuleWithParamLegal(cacheDragChainDTO); // 开始添加规则链信息 TbSysDragChain tbSysDragChain = dragRuleConvert.dragChainDTOToTbSysDragChain(cacheDragChainDTO); tbSysDragChain.setDragRuleChain(dragRuleChain); tbSysDragChain.setChainFileName(fileName); tbSysDragChain.setChainFile(fileBase64Str); tbSysDragChainMapper.insert(tbSysDragChain); // 修改规则链缓存信息 cacheDragChainDTO.setIfLoadDB(RuleConstant.NUM_1_STR); redisUtil.hset(CommonDragRuleConstant.DRAG_RULE_CHAIN_FLAG, cacheDragChainDTO.getUri(), JSONObject.toJSONString(cacheDragChainDTO)); }
-
文件下载
/** * 获取规则文件信息 * * @param uri * @throws IOException */ @Override public void downloadFile(String uri) throws IOException { QueryWrapper<TbSysDragChain> chainQueryWrapper = new QueryWrapper<>(); chainQueryWrapper.lambda().eq(TbSysDragChain::getUri, uri); TbSysDragChain tbSysDragRuleChain = tbSysDragChainMapper.selectOne(chainQueryWrapper); if (ObjectUtil.isNull(tbSysDragRuleChain) || StrUtil.isBlank(tbSysDragRuleChain.getChainFile())) { throw new ServiceException(StrUtil.format("通过uri[{}]获取规则链文件信息为空!", uri)); } // 获取文件信息 String base64FileStr = tbSysDragRuleChain.getChainFile(); String fileName = tbSysDragRuleChain.getChainFileName(); byte[] decodedBytes = Base64.getDecoder().decode(base64FileStr); // 设置响应头信息,比如Content-Type和Content-Disposition response.setContentType(CommonDragRuleConstant.APPLICATION_XML); // 根据实际文件类型设置MIME类型,这里是XML文件 response.setHeader(CommonDragRuleConstant.CONTENT_DISPOSITION, "attachment;filename=\"" + fileName + "\""); try (OutputStream out = response.getOutputStream()) { out.write(decodedBytes); } catch (IOException e) { // 处理IO异常 String errorMessage = LogUtil.getStackTraceInfo(e); throw new ServiceException(StrUtil.format("下载文件异常,异常信息为[{}]", errorMessage)); } finally { response.flushBuffer(); } }
-
获取文件XML信息
/** * 获取规则文件信息 * * @param uri */ @Override public String getXMLStr(String uri) { QueryWrapper<TbSysDragChain> chainQueryWrapper = new QueryWrapper<>(); chainQueryWrapper.lambda().eq(TbSysDragChain::getUri, uri); TbSysDragChain tbSysDragRuleChain = tbSysDragChainMapper.selectOne(chainQueryWrapper); if (ObjectUtil.isNull(tbSysDragRuleChain) || StrUtil.isBlank(tbSysDragRuleChain.getChainFile())) { throw new ServiceException(StrUtil.format("通过uri[{}]获取规则链文件信息为空!", uri)); } // 获取文件信息 String base64FileStr = tbSysDragRuleChain.getChainFile(); byte[] decodedBytes = Base64.getDecoder().decode(base64FileStr); return new String(decodedBytes, StandardCharsets.UTF_8); }