springboot将文件插入到指定路径文件夹,判断文件是否存在以及根据名称删除
解决方案:
直接使用File和数据流实现
1.插入这个是我自己的业务我是将文件转成pdf之后存入指定路径了这个路径是直接定义在了yml里然后在需要的地方注入调用,然后通过file创建空白pdf放到数据流通过:aspose的方法保存file:upload:dir: D:/data/uploads # 通用文件上传目录pdfDir: D:/data/uploadPDF # PDF文件专用目录dowFile: C:\Users\Lenovo\Desktop #下载路径@Value("${file.upload.pdfDir}") private String uploadDirPDF; String fullSourcePath = uploadDir + File.separator + fileName; String fullPdfPath = uploadDirPDF + File.separator + pdfFileName;public static void docToPdf(String sourcerFile,String targetFile) {if (!getLicense()) {// 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();File file = new File(targetFile); //新建一个空白pdf文档BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));Document doc = new Document(sourcerFile); //sourcerFile是将要被转化的word文档doc.save(out, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换out.close();long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时} catch (Exception e) {e.printStackTrace();} }2.判断文件是否存在 获取路径传入file即可然后调用exists返回来的内容就可以实现 File pdfDir = new File(uploadDirPDF); if (!pdfDir.exists() && !pdfDir.mkdirs()) {fileData.setRemark("无法创建PDF目录: " + uploadDirPDF);return fileData; }3.根据名称删除文件 先将数据库的内容删除,数据库删除没有错误成功后删除文档,将名称和路径传入到方法里调用file.delete即可 @RequestMapping("/delMenusTree") public R delMenusTree(@RequestBody MenuDeleteDTO menuDeleteDTO){String msg= biddingtoolsoftwareService.delMenusTree(menuDeleteDTO.getId());if (msg.equals("删除成功")){String mlname = menuDeleteDTO.getMlname();deleteFileIfExists(uploadDir, mlname);deleteFileIfExists(uploadDirPDF, mlname);}return R.ok(msg); } private void deleteFileIfExists(String directory, String fileName) {if (fileName == null || fileName.isEmpty()) {return; // 避免空文件名导致异常}File file = new File(directory, fileName);if (file.exists() && file.isFile()) {if (file.delete()) {log.info("成功删除文件: {}", file.getAbsolutePath());} else {log.error("删除文件失败: {}", file.getAbsolutePath());// 可以选择记录日志或返回更详细的错误信息}} }