欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-16 17:30:34
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; }
}