springboot项目构建成jar运行,如何正确读取resource里的文件
springboot 项目在打包成jar 文件后运行在服务器上后是无法读取到 jar 文件中的内容的
总结了一般有如下四种读取文件的方式:
第一种
classpathresource classpathresource = new classpathresource("excletemplate/test.xlsx"); inputstream inputstream = classpathresource.getinputstream();
第二种
inputstream inputstream = thread.currentthread().getcontextclassloader().getresourceasstream("excletemplate/test.xlsx");
第三种
inputstream inputstream = this.getclass().getresourceasstream("/excletemplate/test.xlsx");
第四种
file file = resourceutils.getfile("classpath:excletemplate/test.xlsx"); inputstream inputstream = new fileinputstream(file);
前三种方法在开发环境(ide中)和生产环境(linux部署成jar包)都可以读取到,第四种只有开发环境 时可以读取到,生产环境读取失败。
推测主要原因是springboot内置tomcat,打包后是一个jar包,无法直接读取jar包中的文件,读取只能通过类加载器读取。
前三种都可以读取到其实殊途同归,直接查看底层代码都是通过类加载器读取文件流,类加载器可以读取jar包中的编译后的class文件,当然也是可以读取jar包中的excle模板了。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
海报
111