1、加载pom
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.31</version>
</dependency>
2、代码
package com.tools.util;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;
import java.io.Closeable;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
@Slf4j
public class YamlUtils {
public static Map<String, Object> get(String yamlFilePath) {
Yaml yaml = new Yaml();
Map<String, Object> map = yaml.load(getInputStream(yamlFilePath));
return map;
}
public static Map<String, Object> get(InputStream ins) {
Yaml yaml = new Yaml();
Map<String, Object> map = yaml.load(ins);
return map;
}
public static Object getValue(String yamlFileName, String... keys) {
Object obj = get(yamlFileName);
if (StrUtil.isAllEmpty(keys)) {
return obj;
}
for (String key : keys) {
if (obj instanceof Map) {
obj = ((Map<String, Object>) obj).get(key);
} else {
return obj;
}
}
return obj;
}
public static void close(Closeable closeable) {
if (null != closeable) {
try {
closeable.close();
} catch (Exception e) {
}
}
}
private static InputStream getInputStream(String yamlFilePath) {
InputStream ins = null;
try {
ins = Thread.currentThread().getContextClassLoader().getResourceAsStream(yamlFilePath);
if (null == ins) {
log.warn(">>>>>>>>> Thread.currentThread().getContextClassLoader().getResourceAsStream({}) is null !", yamlFilePath);
ins = YamlUtils.class.getClassLoader().getResourceAsStream(yamlFilePath);
if (null == ins) {
log.warn(">>>>>>>>> YamlUtils.class.getClassLoader().getResourceAsStream({}) is null !", yamlFilePath);
ins = Objects.requireNonNull(YamlUtils.class.getResourceAsStream(yamlFilePath));
}
}
} catch (Exception e) {
log.error("[x] File not found ! {}", yamlFilePath, e);
} finally {
close(ins);
}
return ins;
}
}