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

Posted _Phoenix

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
 File newFile = new File(newFilePath + ftlName); if (newFile.isFile() && newFile.exists()) { return newFilePath; } 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; }
}

 







以上是关于spring boot 打jar包,获取resource路径下的文件的主要内容,如果未能解决你的问题,请参考以下文章

spring boot打jar包运行,加载jar包外部的页面以及静态资源文件

spring boot打jar包发布

Spring Boot发布将jar包转为war包。

spring boot 打jar包分离lib和resources

springboot2.0+dubbo-spring-boot-starter聚合项目打可执行的jar包

Spring Boot打jar包,排除lombok等scope=provided的依赖