java 打包后 文件资源文件 jar_解决SpringBoot打成jar运行后无法读取resources里的文件问题...

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

6b65ebedf4df25352eed4a24a16dd321.png

在开发环境中通过下面方法能读取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内部的路径在这里插入图片描述

48ad61eb31a77ef3b47d9cc22c45f63c.png

怎么解决

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情况

src/main/java

**/*.properties

**/*.xml

**/*.yml

false

src/main/resources

**/*.*

false

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

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

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

public static void test(){

List oldList = new ArrayList(){{add(1);add(2);add(4);add(5);}};

List newList = new ArrayList(){{add(3);add(4);add(5);add(6);}};

Map 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 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里的文件问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值