最近项目中有个需求:先加载excel模版文件,然后填充数据再下载。模版文件是提前做好的,首先想到是放在服务器的硬盘上,
通过 new File("/xxx/xxxx.xls") 这种方式就可以拿到。但是项目用的是docker ,每次服务重启构建都要重新上传,太麻烦。所以还是放到项目里面比较方便,项目用的springboot,静态文件放到resource目录下面。
通过这种方式拿到文件: File file = new File(this.getClass().getClassLoader().getResource("template/export.xls").getFile());
本地测试ok ,但是到了服务上 报错:file not found。
什么情况?方式不对?ok 我换一种方式读取
ClassPathResource classPathResource = new ClassPathResource("template/export.xls");
File file = classPathResource.getFile();
本地测试ok,服务器还是报错:file not found。
经研究发现,服务器上是jar包,访问里面到静态文件必须要通过流到方式读取文件。
扫描二维码关注公众号,回复:
5167928 查看本文章
所以要用这种方式读取文件:
ClassPathResource classPathResource = new ClassPathResource("template/export.xls");
InputStream initialStream = classPathResource.getInputStream();