spring-boot以jar包方式时读取resource或是template文件

1.项目场景:

以jar包方式部署系统,想读取resource或是template下面的文件时,报 File Not Found
我遇到的情况是,整个项目达成了一个包,在开发环境(windows + idea)读取文件没问题,但在预发布环境(centos, 打成一个jar部署),则报错。


2.问题描述:

File file = ResourceUtils.getFile("classpath:templates/jumppage.html")

使用上述方法读取模板文件当部署成jar包时读取不到文件


3.原因分析:

不祥,欢迎懂得小伙伴给出留言


4.解决方案:

方法1/2/3在开发环境、预发布环境都可以读取到jar包中的文件,方法4则只有开发环境中可以、直接从jar包读取失败。

4.1方法一

InputStream in = null;
ClassPathResource classPathResource = new ClassPathResource("templates/jumppage.html");
in = classPathResource.getInputStream();
StringBuffer buff = new StringBuffer();
byte[] filecontent = new byte[1024];
while((in.read(filecontent)) != -1){
    String strRead = new String(filecontent);
    buff.append(strRead);
}
byte[] bytes = buff.toString().getBytes();

注:使用classPathResource.getFile()会报错找不到该文件,原因是springboot打成了jar包,classPathResource.getFile()无法读取jar包目录下的文件

4.2方法二

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("templates/jumppage.html");

4.3方法三

InputStream inputStream = this.getClass().getResourceAsStream("/templates/jumppage.html");

4.4方法四

File file = ResourceUtils.getFile("classpath:templates/jumppage.html");
InputStream inputStream = new FileInputStream(file);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值