Springboot 生产环境下读取Resource下的文件
在springboot中读物resource下的文件,ResourceUtils.getFile()是个很好用的方法,直接获取resource下的文件,用法如下:
File file = ResourceUtils.getFile("classPath:static/img/logo.png");
方法很好用,但是在使用maven将项目打包为jar运行后会发现,此方法会爆出FileNotFoundException错误
Caused by: java.io.FileNotFoundException: class path resource [abc.xml] cannot be resolved to
absolute file path because it does not reside in the file system: jar:file:/D:/project/ems/ta
rget/ems-1.0.0.jar!/BOOT-INF/classes!/static/img/logo.png
原来ResourceUtils.getFile读取的是绝对路径,是jar包内的路径,所以无法获取文件。于是想到可以通过ResourceLoader来读取文件,但是ResourceLoader读取的文件是流,于是进一步将流转换为文件方便操作。
ResourceLoader resourceLoader = new DefaultResourceLoader();
InputStream inputStream = resourceLoader.getResource("static/img/logo.png").getInputStream();
//通过将文件转换为临时文件进行操作
File file = File.createTempFile("logo", ".png");
try {
FileUtils.copyInputStreamToFile(inputStream, file);
} finally {
//关闭IO
IOUtils.closeQuietly(inputStream);
}
至此,Springboot在生产环境中读取文件功能实现。