liran123

前言:最近在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包时的文件路径结构

 

 

分类:

技术点:

相关文章: