现象
以jar包方式部署系统,想读取resource或是template下面的文件时,报 File Not Found
我遇到的情况是,整个项目达成了一个包,在开发环境(windows + idea)读取文件没问题,但在预发布环境(centos, 打成一个jar部署),则报错。
使用
jar -xvf xxx.jar
命令解压jar后,大体结构如下:
BOOT-INF
META-INF
org
...
继续往下找可以找到我想要读取的资源文件,说明打包正常,那只能说明:
以jar形式部署后,采用一般的java 读取文件的API接口,可能无法从jar包直接读取到文件。
解决
定位到是读取文件方式问题后,试验了几种,以下都列下:
方法1
ClassPathResource classPathResource = new ClassPathResource("excelTemplate/test.xlsx");
InputStream inputStream =classPathResource.getInputStream();
方法2
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excelT