Java读取yaml数据

YAML

YAML 数据结构可以用类似大纲的缩排方式呈现,结构通过缩进来表示,连续的项目通过减号“-”来表示,map结构里面的key/value对用冒号“:”来分隔。

下面介绍两种 Java 读取 Yaml 内容的方式:

1.SnakeYaml

忽略注释的方式,读写会导致注释丢失

  • 在pom.xml加入snakeyaml依赖:
      <!-- read and write yaml file -->
      <dependency>
		    <groupId>org.yaml</groupId>
		    <artifactId>snakeyaml</artifactId>
		    <version>1.29</version>
      </dependency>
  • 具体java代码:
public class YamlUtils {
    
    
    private static final Logger logger = LoggerFactory.getLogger(YamlUtils.class);

    // yml2Map: Yaml to Map, 将yaml文件读为map
    public static Map<String, Object> yml2Map(String path) throws FileNotFoundException {
    
    
        FileInputStream fileInputStream = new FileInputStream(path);
        Yaml yaml = new Yaml();
        Map<String, Object> ret = (Map<String, Object>) yaml.load(fileInputStream);
        return ret;
    }

    // map2Yml: Map to Yaml, 将map转换为yaml格式
    public static void map2Yml(Map<String, Object> map, String path) throws IOException {
    
    

        File file = new File(path);
        FileWriter fileWriter = new FileWriter(file);
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml yaml = new Yaml(options);
        yaml.dump(map, fileWriter);
    }
 }

2.eo-yaml:

  • 支持注释读写的yaml包;
  • 读取的时候,生成节点,在每一个节点上保存相应的注释;
  • 写入的时候,根据节点,重新添加相应的注释;
<dependency>
    <groupId>com.amihaiemil.web</groupId>
    <artifactId>eo-yaml</artifactId>
    <version>4.3.5</version>
</dependency>
YamlMapping team = Yaml.createYamlInput(
    new File(path)
).readYamlMapping();
String architect = team.string("architect");
YamlSequence devs = team.yamlSequence("developers");
YamlSequence devops = team.yamlSequence("devops");
Map<String, Integer> grades = new HashMap<>();
grades.put("Math", 9);
grades.put("CS", 10);
YamlMapping student = Yaml.createYamlDump(
    new Student ("John", "Doe", 20, grades)
).dumpMapping();

猜你喜欢

转载自blog.csdn.net/twi_twi/article/details/129949480