SpringBoot不要使用ResourceUtils读取资源文件

如题,在SpringBoot中尽量避免使用ResourceUtils读取资源文件。在一次开发过程中,我需要读取位于resource目录中的图片文件,代码如下:

File logoFile = ResourceUtils.getFile("classpath:image"+File.separator+"logo.png");

//...

在windows电脑中,这段代码可以正常读取到我需要的文件,但是等到项目部署到centOS系统上时,这段代码就不能正常工作了,经过大量查阅资料,最终在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.

 这段话的核心意思是:getFile()不能嵌套在jar文件中,如果需要在SpringBoot项目中读取资源文件,最好使用getInputStream()。了解到这些后,我把上诉代码改成如下:

ClassPathResource cpr = new ClassPathResource("image"+File.separator+"logo.png");
InputStream in = cpr.getInputStream();

最终顺利的解决了问题。

你可能感兴趣的:(SpringBoot)