yaml可读性强,简洁方便。
一、基本语法如下:
1.子节点,键和值之间“冒号+空格分隔”(: )千万不要忘记空格了
2.父节点与回车键,默认识别时就当空格了
3.字符串无需引号""引起来,但是如果字符串中包含空格就必须加引号""
server:
url: 192.168.0.2
port: 8989
login:
token: 3ty123456
被解析出来其实是这样的
{server={url=192.168.0.2, port=8989}, login={token=3ty123456}}
二、思路解析
1.需要导入snakeyaml包
2.获取内容,调用yaml.load()方法
3.写入和修改调用yaml.dump()方法
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
package test.utils;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class YmlUtil {
private static Map<String, Map<String, Object>> properties;
private static FileInputStream fis = null;
private static File f = null;
static {
try {
f=new File("F:\\autoInterface\\src\\resources\\application.yaml");
fis = new FileInputStream(f);
properties = new HashMap<>();
Yaml yaml = new Yaml();
properties = yaml.load(fis);
System.out.println("properties的值为:"+properties);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*获取字段名下的key对应的值
* @param section 字段名
* @param key 键
* @return
*/
public Object getValueByKey(String section, String key) {
System.out.println("properties的值为:"+properties);
Map<String, Object> rootproperty = properties.get(section);
System.out.println("rootproperty的值为:"+rootproperty);
return rootproperty.getOrDefault(key,"");
}
/**
* yaml文件修改
* @param section
* @param key
* @param value
* @return
*/
public boolean updateYaml(String section,String key, Object value ){
Yaml yaml = new Yaml();
Map<String, Object> before_property = properties.get(section);
before_property.remove(key);
before_property.put(key, value);
try {
yaml.dump(properties,new FileWriter(f));
return true;
}catch (Exception e){
}
return false;
}
/**
* yaml文件新增
* @param section
* @param key
* @param value
* @throws IOException
*/
public void write(String section ,String key,String value) throws IOException {
Map<String,Map<String, Object>> map = new HashMap<String,Map<String, Object>>();
Map<String, Object> mapchild = new HashMap<String,Object>();
mapchild.put(key, value);
map.put(section,mapchild);
Yaml yml = new Yaml();
FileWriter writer = new FileWriter("F:\\autoInterface\\src\\resources\\application.yaml", true);
BufferedWriter buffer = new BufferedWriter(writer);
buffer.newLine();
yml.dump(map, buffer);
buffer.close();
writer.close();
}
public static void main(String[] args) throws IOException {
YmlUtil ymlUtil = new YmlUtil();
ymlUtil.updateYaml("login2","token2","value1");
}
}
最终修改完的结果是这样的,感觉回不到原来的yaml文件标准格式了,如果有好的方法,欢迎留言
server: {url: 192.168.0.2, port: 8989}
login: {token: 3ty123456}
login2: {token2: value1}