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());
            // 可以选择记录日志或返回更详细的错误信息
        }
    }
}
相关推荐
王八八。6 小时前
linux后台java、postSQL部署命令
java·linux·运维
月落归舟6 小时前
MyBatis缓存机制
java·缓存·mybatis
鹿导的通天塔6 小时前
99%的人都不知道Codex 的 goal 神技!完整设置及提示词模板教学
后端
huipeng9266 小时前
企业级微服务开发实战(一):项目启动与工程化设计
java·开发语言·spring boot·spring cloud·微服务·云原生·架构
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ7 小时前
java实现excel导入、下载模板方法
java·开发语言·excel
段ヤシ.8 小时前
回顾Java知识点,面试题汇总Day12(持续更新)
java·mybatis
ltl8 小时前
Transformer 原论文怎么训出来的:8 张 P100、12 小时、warmup 4000 步
后端
why技术8 小时前
AI Coding开始进入第四个时代,我还没上车呢!
前端·人工智能·后端
java1234_小锋8 小时前
Spring AI 2.0 开发Java Agent智能体 - MCP(模型上下文协议)
java·人工智能·spring·spring ai
seven97_top8 小时前
两小时入门Sentinel
java·sentinel