SpringBoot项目打包,部署获取不到resource目录下文件错误

489 阅读1分钟

问题描述

由于项目增加https,所以在resource目录下增加个客户端认证文件,本地开发没问题,打jar包或者docker镜像部署就会报错,异常信息如下:

Exception:java.lang.IllegalArgumentException: URI is not hierarchical
class path resource [xxxx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxxx.jar!/BOOT-INF/classes!xxxx

报错很明显,肯定是读取不到配置文件了。

问题原因

原始代码:

String txt = "";
Resource resource = new ClassPathResource("templates/layout/email.html");
File file = resource.getFile();

经过debug分析发现:

71188.png 该方法使用的协议是个jar而不是file就会抛出FileNotFoundException

解决方式

  • 使用流操作
String txt = "";
Resource resource = new ClassPathResource("templates/layout/email.html");
InputStream in = resource.getInputStream();
File inuModel = new File("/opt/data/config");
FileUtils.copyToFile(inputStream, inuModel);