Java 使用snakeyaml解析yaml
2020-07-20 本文已影响0人
xiaogp
下载依赖
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
在项目根目录下创建/etc/conifg.yml 配置文件, 输入一条测试数据
test.param: 3
代码测试
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
public class yamlTest {
public static void main(String[] args) throws FileNotFoundException {
Map conf = new Yaml().load(new FileInputStream(new File("./etc/config.yml")));
System.out.println(conf.get("test.param")); // test_gp2
System.out.println(conf.getOrDefault("test.param2", "unknown")); // unknown
}
}
打包测试
在jar包同级目录下创建/etc/confog.yml文件
root@ubuntu:~/jars# tree etc/ sparktest_gp-1.0-SNAPSHOT.jar
etc/
└── config.yml
sparktest_gp-1.0-SNAPSHOT.jar
运行jar包
root@ubuntu:~/jars# java -cp sparktest_gp-1.0-SNAPSHOT.jar main.yamlTest
2
unknown
修改/etc/config.yml文件
test.param: 3
重新运行jar包, 参数改变, 可以在jar包外部修改配置
root@ubuntu:~/jars# java -cp sparktest_gp-1.0-SNAPSHOT.jar main.yamlTest
3
unknown
使用单例模式构建读取配置工具类
package main;
import com.ctc.wstx.api.ReaderConfig;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
public class Config {
private Map conf;
private static Config instance;
private Config() {
try {
conf = new Yaml().load(new FileInputStream(new File("./etc/config.yml")));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Config getInstance() {
if (instance == null) {
synchronized (ReaderConfig.class) {
if (instance == null) {
instance = new Config();
}
}
}
return instance;
}
public String getString(String param) {
return String.valueOf(conf.get(param));
}
public String getString(String param, String defaultValue) {
if (null == conf.get(param)) {
return defaultValue;
}
return String.valueOf(conf.get(param));
}
public Map getConfig() {
return conf;
}
}
调用测试
import java.util.Map;
public class UseConfig {
public static void main(String[] args) {
Map conf = Config.getInstance().getConfig();
System.out.println(conf);
String parma1 = Config.getInstance().getString("test.param");
System.out.println(parma1);
}
}