版权声明:如果觉得我的博客对你有帮助, 请点赞或评论! https://blog.csdn.net/zongf0504/article/details/88798539
虽然Spring 的ResourcUtils 在开发时可以正确读取配置文件内容, 当时当达成java jar包运行时,却会报文件找不到异常。 建议使用ClassPathResource 读取属性文件。
1. ResourceUtils 读取属性文件
1.1 代码
- 需要注意的时, 文件路径需要添加classpath:前缀。
- 在开发时文件读取正常, 但是当打成jar包之后, 会抛出文件找不到异常
String filePath = "classpath:properties/zookeeper.properties";
File file = ResourceUtils.getFile(filePath);
Properties properties = new Properties();
properties.load(new FileInputStream(file));
1.2 异常
[2019-03-20 13:42:07:451][main][ERROR][c.t.f.m.q.p.ZookeeperProperty]- 解析配置文件失败, 配置文件:classpath:properties/zookeeper.properties
java.io.FileNotFoundException: class path resource [properties/zookeeper.properties] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/workspace/idea/falcon-ms/falcon-ms-quartz/target/falcon-ms-quartz-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/properties/zookeeper.properties
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217)
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:180)
2. ClassPathResource 读取配置文件
- 文件路径不能添加lclasspath 字眼儿
- 打成jar 包之后也可以正常执行
String filePath = "properties/zookeeper.properties";
ClassPathResource resource = new ClassPathResource(filePath);
Properties properties = new Properties();
properties.load(resource.getInputStream());