spring boot 打jar包,获取resource路径下的文件

前言:最近在spring boot项目静态类中获取resource路径下文件,在idea中启动都可以获取,但是打包后变成了jar包 就无法获取到。

    我想到了两种方法,一种是根据http访问静态资源比如:localhost:9080/static/template/xxx.ftl文件。

    另外一种是根据流获取到文件,然后拷贝到新的文件夹下面。下面说的就是第二种方式的代码

 

复制代码
public class DocUtil {
  //此路径是其他方法进行调用,且只需要加载一次
  
private static String sourceTemplatePath;
  // 模板文件名称 位于 resource/static/template下面
private static String[] ftlArray = {"申请书.ftl", "授权委托书.ftl", "法定代表人身份证明书.ftl", "逾期督促申请.xls"}; static {  //静态方法调用一次  sourceTemplatePath = createFtlFileByFtlArray(); } private static String createFtlFileByFtlArray() { String ftlPath = "static/template/"; String path = ""; for (int i = 0; i < ftlArray.length; i++) { path = createFtlFile(ftlPath, ftlArray[i]); if (null == path) { logger.info("ftl not copy success:" + ftlArray[i]); } } return path; } private static String createFtlFile(String ftlPath, String ftlName) { try {
        //获取当前项目所在的绝对路径 String proFilePath
= System.getProperty("user.dir"); logger.info("project run path:" + proFilePath);        //获取模板下的路径 
        String newFilePath = proFilePath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + ftlPath;
        newFilePath = newFilePath.replace("/", File.separator);
        logger.info("newFilePath:" + newFilePath);
        //检查项目运行时的src下的对应路径
      File newFile = new File(newFilePath + ftlName);
        if (newFile.isFile() && newFile.exists()) { 
          
return newFilePath;
          }
        //当项目打成jar包会运行下面的代码,并且复制一份到src路径下(具体结构看下面图片)
        InputStream certStream
= Thread.currentThread().getContextClassLoader().getResourceAsStream(ftlPath + ftlName);
        
byte[] certData = IOUtils.toByteArray(certStream);
        FileUtils.writeByteArrayToFile(newFile, certData);
return newFilePath; } catch (IOException e) { logger.error("复制ftl文件失败--> 异常信息:" + e); } return null; }
}
复制代码

 项目打成jar包时的文件路径结构

 

 

posted @   _Phoenix  阅读(24480)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示