首页 技术 正文
技术 2022年11月16日
0 收藏 796 点赞 4,373 浏览 1681 个字

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

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,498
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,911
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,745
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,501
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,139
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,303