- 方式一(使用Spring的读取方式):
1、pom.xml中添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
2、java程序中使用
YamlPropertiesFactoryBean yamls = new YamlPropertiesFactoryBean();
yamls.setResources(new ClassPathResource("application-beta.yml"));
Properties properties = yamls.getObject();
System.out.println((String) properties.get("test.on"));
- 方式二(只使用snakeyaml原生依赖包):
1、引入依赖
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.27</version>
</dependency>
2、读取工具类
import org.codehaus.plexus.util.StringUtils;
import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.Map;
/**
* @since 2021/1/6 11:45
*/
public class YamlReaderUtils {
private static Map<String,String> result;
public static Map<String,String> getYamlByFileName(String fileName) throws Exception{
Yaml yaml = new Yaml();
InputStream is = new FileInputStream(fileName);
int lineNumber = (int) getFileLineNum(fileName);
result = new HashMap<>(lineNumber);
Map<String,Object> params = yaml.loadAs(is,Map.class);
for(Map.Entry<String,Object> entry : params.entrySet()){
if(entry.getValue() instanceof Map){
eachYaml(entry.getKey(),(Map<String,Object>)entry.getValue());
}else{
result.put(entry.getKey(),entry.getValue().toString());
}
}
return result;
}
/**
* 使用递归进行深度转换,将Map<String,Object>转换为Map<String,String>;
* @param key 父级key
* @param map 父级entry
*/
private static void eachYaml(String key,Map<String,Object> map){
for (Map.Entry<String,Object> entry : map.entrySet()){
String newKey = "";
if(StringUtils.isNotEmpty(key)){
if(!(entry.getKey() instanceof String)) {
newKey = (key + "." + String.valueOf(entry.getKey()));
} else {
newKey = (key + "." + entry.getKey());
}
}else{
newKey = entry.getKey();
}
if(entry.getValue() instanceof Map){
eachYaml(newKey,(Map<String,Object>)entry.getValue());
}else{
result.put(newKey,entry.getValue().toString());
}
}
}
/**
* 根据key 获取指定的值(默认文件)
*/
public static String getValue(String key) throws Exception {
if(result == null || result.size() <= 0 || StringUtils.isBlank(result.get(key))){
return null;
}
return result.get(key);
}
/**
* 根据key 获取指定的值(指定文件)
*/
public static String getValue(String fileName,String key) throws Exception {
if(result == null || result.size() <= 0 ){
getYamlByFileName(fileName);
}
if(result == null || StringUtils.isBlank(result.get(key))){
return null;
}
return result.get(key);
}
/**
* 获取文件行数
* @param filePath
* @return
*/
public static long getFileLineNum(String filePath) {
try (LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(filePath))){
lineNumberReader.skip(Long.MAX_VALUE);
int lineNumber = lineNumberReader.getLineNumber();
return lineNumber + 1;
} catch (IOException e) {
return -1;
}
}
}
3、java程序中使用(略)