Springboot YAML文件数据与Map互转
在目前的项目中,yaml文件作为配置文件已是很常见,例如k8s中的 pod、deployment、service等等组件的创建可通过执行yaml文件创建。废话不多说 先上代码:import com.alibaba.fastjson.JSONObject;import org.junit.Test;import org.junit.runner.RunWith;import org...
·
在目前的项目中,yaml文件作为配置文件已是很常见,例如k8s中的 pod、deployment、service等等组件的创建可通过执行yaml文件创建。
废话不多说 先上代码:
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringRunner;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
Yaml yaml = new Yaml();
Resource resource = new ClassPathResource("b.yaml"); //读取resources文件夹中的yaml文件
Object result = null;
InputStream in = null;
try {
// File file = resource.getFile();
File dumpfile = new File("/Users/wyg/Desktop/b.yaml");
in = new FileInputStream(dumpfile);
result = yaml.load(in);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Map<String,String> resmap = (Map<String, String>) result;
System.out.println(JSONObject.toJSONString(resmap));
// 将数据写入yaml文件
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml wyaml = new Yaml(dumperOptions);
File dumpfile = new File("/Users/wyg/Desktop/b.yaml");
try(FileWriter writer = new FileWriter(dumpfile)) {
wyaml.dump(resmap, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)