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);