springboot读取resources目录下的文件
记录一次问题
背景:项目中需要做按照固定的Word模板导出,所以我把word模板,放在了resources目录下面。然后,读取这个模板。
本地环境是好的,但是部署测试环境的时候,除了问题。
原本的读取方式:
File file = ResourceUtils.getFile(“classpath:file/shbg.docx”);
测试环境直接报错,经过百度之后改成了:
ClassPathResource resource = new ClassPathResource("file/shbg.docx");
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
获得当前的类加载器,通过类加载器读取文件流。
(或者一下两种方法)
1
InputStream io = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(“test.txt”);
2
InputStream io = getClass().getClassLoader().getResourceAsStream(“test.txt”);