零、背景

做的一个下载导入模版的功能,在本地(Windows)下都是可以的,部署到测试环境(Centos7)后报500。因为模版的一部分是动态生成的,需要先从resources目录下获取到原模版文件,但是,因为项目是打包成jar运行的,在Centos7下会找不到文件。

一、错误示范

Resource resource = new ClassPathResource("static/templates/" + filename);
...
File file = resource.getFile();

查阅大量资料后发现,getFile()这个方法需要文件本身存在于文件系统中(也就是硬盘上),而我们是获取jar包中的文件,所以通过这种方式是获取不到的。

国外stackoverflow上网友的一段话:

resource.getFile() expects the resource itself to be available on the file system, i.e. it can't be nested inside a jar file. 
This is why it works when you run your application in STS but doesn't work once you've built your application and run it from the executable jar. 
Rather than using getFile() to access the resource's contents, I'd recommend using getInputStream() instead. 
That'll allow you to read the resource's content regardless of where it's located.

二、解决方案

大部分情况下,我们是要获取文件中的数据,也就是文件流,所以我们直接获取InputStream即可。

InputStream is = resource.getInputStream();


赞助本站,网站的持续发展离不开你们的支持!一分也是爱ヾ(◍°∇°◍)ノ゙
 本文链接: ,花了好多脑细胞写的,转载请注明链接喔~~
登陆
      正在加载评论