这篇文章主要介绍了如何基于JAVA读取yml配置文件指定key内容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
先引入需要的依赖
org.yaml
snakeyaml
1.23
读取YML文件工具类的代码
import org.apache.commons.;
import org.;
import org.;
import ;
import ;
import .*;
import ;
import ;
import ;
/**
* @author hunmeng
* @create 2020-01-10 20:34
*/
public class YmlUtils {
private static final Logger LOGGER = ();
private static String bootstrap_file = "classpath:";
private static Map result = new HashMap<>();
/**
* 根据文件名获取yml的文件内容
* @param filePath
* @param keys 第一个参数对应第一个key,第二个参数对应第二个key 比如下的所有 就是两个参数、
* getYmlByFileName(bootstrap_file,"spring", "name");
* @return
*/
public static Map getYmlByFileName(String filePath, String... keys) {
result = new HashMap<>();
if(filePath == null) filePath = bootstrap_file;
InputStream in = null;
try {
File file = (filePath);
in = new BufferedInputStream(new FileInputStream(file));
Yaml props = new Yaml();
Object obj = (in,);
Map param = (Map) obj;
for( entry:()){
String key = ();
Object val = ();
if ( != 0 && !keys[0].equals(key)){
continue;
}
if(val instanceof Map){
forEachYaml(key,(Map) val, 1, keys);
}else{
(key, ());
}
}
return result;
} catch (FileNotFoundException e) {
((),e);
}finally {
if (in != null){
try {
();
} catch (IOException e) {
((),e);
}
}
}
return null;
}
/**
* 根据key获取值
* @param key
* @return
*/
public static String getValue(String key) throws FileNotFoundException {
Map map = getYmlByFileName(null);
if(map==null)return null;
return (key);
}
/**
* 遍历yml文件,获取map集合
* @param key_str
* @param obj
* @param i
* @param keys
* @return
*/
public static Map forEachYaml(String key_str,Map obj, int i, String... keys){
for( entry:()){
String key = ();
Object val = ();
if ( > i && !keys[i].equals(key)){
continue;
}
String str_new = "";
if((key_str)){
str_new = key_str+ "."+key;
}else{
str_new = key;
}
if(val instanceof Map){
forEachYaml(str_new,(Map) val, ++i, keys);
i--;
}else{
(str_new,());
}
}
return result;
}
/**
* 获取bootstrap.yml的name
* @return
*/
public static String getApplicationName() throws FileNotFoundException {
return getYmlByFileName(bootstrap_file).get("server.port");
}
/**
* 获取的name
* @return
*/
public static String getApplicationName1() throws FileNotFoundException {
String name = getYmlByFileName(bootstrap_file).get("");
return name + "center";
}
public static void main(String[] args) throws FileNotFoundException {
Map ymlByFileName = getYmlByFileName(bootstrap_file,"spring");
Set> entries = ();
for ( entry : entries) {
(()+"==="+());
}
(getApplicationName());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。