ClassPathResource.getFile()在jar包中运行报错cannot be resolved to absolute file path

    最近在Springboot项目中做一个导出Excel表格的功能,表格数据保存在Resoure目录下,在java代码中使用ClassPathResource.getFile()获取文件,本地可以正常进行获取到并且导出。但是当把项目打成jar包之后运行发现导出出错,查看控制台报错发现找不到路径,报错信息如下:

    从上图可以看出,jar包单独运行的时候使用ClassPathResource.getFile()找不到绝对路径,从报错信息中可以看到绝对路径为:jar:file:/D:server-back/monitor_platform/monitor_platform-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/download/

这是一个以jar:开头的路径,在Windows系统中肯定是找不到的,Windows下面可以通过file:开头也就是在浏览器中可以通过file协议找到本机中的文件,但是即使是去掉报错路径前面的jar:也是找不到文件的。那么问题究竟出在那里了呢?通过翻阅各种资料找到了一句话:

       resource.getFile() expects the resource itself to be available on the file system, i.e. it can't be nested inside a jar file. This is why it works when you run your application in STS but doesn't work once you've built your application and run it from           the executable jar. Rather than using getFile() to access the resource's contents, I'd recommend using getInputStream() instead. That'll allow you to read the resource's content regardless of where it's located.

从上面一段话可以看出:使用getFile()方法必须保证在当前文件系统上可以获取到的,显然、这个文件不能在jar文件中。这就是为什么在jar包中不能使用getFile()为此可以推荐使用 getInputStream()方法。因为使用getInputStream()方法可以允许你读取资源内容而不用管他在什么位置;

    这段话说的特别清楚,然后我尝试着改getFile()->getInputStream()方法后,重新打jar包,启动测试,问题解决。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值