jar部署的SpringBoot项目,加载项目资源文件时,异常信息提示,文件路径包含jar包,导致文件找不到
*.jar!/templates/img/logo.png
1、功能需求描述
发送邮件时,邮件内容模板中包含图片文件,图片文件加载问题
-- 图片文件路径说明
resources
-templates
--img
---logo.png
2、问题描述
- 在IDEA开发环境测试时,使用以下代码加载resources目录下的logo.png图片文件没有任何问题
Map<String, FileSystemResource> filesMap = new HashMap(1);
try {
// 正文模板中的图片
Resource imgResource = new ClassPathResource("templates" + File.separator + "img" + File.separator + "logo.png");
FileSystemResource imgFile = new FileSystemResource(imgResource.getFile());
filesMap.put("logo", imgFile);
} catch (IOException e) {
log.error("[MuscleapeError] the image in email template load fail");
e.printStackTrace();
}
- 服务器使用的DOCKER部署生成的jar文件,运行时出现报错信息:
java.io.FileNotFoundException: class path resource [templates/img/logo.png] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/usr/local/tomcat/webapps/ROOT/WEB-INF/lib/engine-core-bll-manager-1.0.jar!/templates/img/logo.png
3、解决办法
参考:https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar
参考:https://www.oschina.net/question/2272552_2269641
// 第一种实现方式
String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException", e);
}
// =========================================================================
// 第二种实现方式
ClassPathResource classPathResource = new ClassPathResource("static/something.txt");
InputStream inputStream = classPathResource.getInputStream();
File somethingFile = File.createTempFile("test", ".txt");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
// =========================================================================
// 第三种实现方式
Resource[] resources;
try {
resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "/*.json");
for (int i = 0; i < resources.length; i++) {
try {
InputStream is = resources[i].getInputStream();
byte[] encoded = IOUtils.toByteArray(is);
String content = new String(encoded, Charset.forName("UTF-8"));
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
根据以上第二种实现方法,改造问题代码为:
Map<String, FileSystemResource> filesMap = new HashMap(1);
ClassPathResource imgResource = new ClassPathResource("templates" + File.separator + "img" + File.separator + "logo.png");
try (InputStream inputStream = imgResource.getInputStream()) {
// 正文模板中的图片
File imageFile = File.createTempFile("logo", ".png");
FileUtils.copyInputStreamToFile(inputStream, imageFile);
FileSystemResource imgFile = new FileSystemResource(imageFile);
filesMap.put("logo", imgFile);
} catch (IOException e) {
log.error("[MuscleapeError] the image in email template load fail");
e.printStackTrace();
}
网友评论