当前位置: 移动技术网 > IT编程>开发语言>Java > 解决SpringBoot打成jar运行后无法读取resources里的文件问题

解决SpringBoot打成jar运行后无法读取resources里的文件问题

2020年08月19日  | 移动技术网IT编程  | 我要评论
开发一个word替换功能时,因替换其中的内容功能需要 word 模版,就把 word_replace_tpl.docx 模版文件放到 resources 下在开发环境中通过下面方法能读取word_re

开发一个word替换功能时,因替换其中的内容功能需要 word 模版,就把 word_replace_tpl.docx 模版文件放到 resources 下

在开发环境中通过下面方法能读取word_replace_tpl.docx文件,但是打成jar包在 linux下运行后无法找到文件了

file file = resourceutils.getfile(resourceutils.classpath_url_prefix + "static/office_template/xxx.docx");

在开发环境运行时,会把资源文件编译到 项目\target\classes\static\office_template\xxx.docx 目录下,但是打包成jar后,

resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它是位于jar内部的一个路径。所以通过resourceutils.getfile或者this.getclass().getresource("")方法无法正确获取文件。

我们用压缩软件打开 jar 文件,看看该word模版位于jar内部的路径在这里插入图片描述

怎么解决

1.把该模版文件放到jar项目外,在项目中配置该模版文件的绝对路径,不太推荐这种方式,可能会忘记配置模版

2.通过 classpathresource resource = new classpathresource(“static/office_template/word_replace_tpl.docx”);方式读取

用第二种方式读取jar中的文件流

classpathresource resource = new classpathresource("static/office_template/word_replace_tpl.docx");
file sourcefile = resource.getfile();
inputstream fis = resource.getinputstream();

还要在项目pom.xml中配置resources情况

<build>
 <!-- 定义包含这些资源文件,能在jar包中获取这些文件 -->
 <resources>
 <resource>
 <directory>src/main/java</directory>
 <includes>
 <include>**/*.properties</include>
 <include>**/*.xml</include>
 <include>**/*.yml</include>
 </includes>
 <!--是否替换资源中的属性-->
 <filtering>false</filtering>
 </resource>
 <resource>
 <directory>src/main/resources</directory>
 <includes>
 <include>**/*.*</include>
 </includes>
 <!--是否替换资源中的属性-->
 <filtering>false</filtering>
 </resource>
 </resources>
 </build>

再次发布项目,访问功能,测试后已经在服务器上能读取模版文件并生成出新文件了

补充知识:两个list高效取出其中新增和相同的数

两个list循环,尽量避免双层循环以及contains的使用

public static void test(){
    list<integer> oldlist = new arraylist<integer>(){{add(1);add(2);add(4);add(5);}};
    list<integer> newlist = new arraylist<integer>(){{add(3);add(4);add(5);add(6);}};
    map<integer,integer> map = new hashmap<>();

    for (integer i: oldlist ) {
      map.put(i,0);
    }
    system.out.print(map);

    for (integer j: newlist ) {

      //value为1 ,更新的数据
      if (map.containskey(j)){
        map.put(j,1);
      }else {
        //value为2 ,新增的数据
        map.put(j,2);
      }
    }
    system.out.println(map);
    for (map.entry<integer,integer> entry: map.entryset() ) {
      if(entry.getvalue().equals(0)){
        system.out.println("旧的值:"+entry.getkey());
      }
      if(entry.getvalue().equals(1)){
        system.out.println("更新的值:"+entry.getkey());
      }
      if(entry.getvalue().equals(3)){
        system.out.println("新增的值:"+entry.getkey());
      }
    }

    system.out.println(map);
  }

  public static void main(string[] arg){
    test();
  }

以上这篇解决springboot打成jar运行后无法读取resources里的文件问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网