JYaml文件流读取/写入Yaml配置文件


yaml配置文件格式规范:- 表示sequence(list列表结构),: 表示map键值对
1
#以下是示例yaml结构

age: 23
children: 
  - 
    age: 8
    name: mary1
    sex: man
  - 
    age: 9
    name: simon2
    sex: fatel
name: simon.zhang
sex: man
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1.准备工作,创建Persion实体类

package com.yaml.entity;

import java.util.List;

/**
 * Created by simon on 16-6-12.
 */
public class Person {
    private String name;
    private int age;
    private String Sex;
    private List<Person> children;

    //省略 getter and setter method.....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2.实现读取/写入yaml配置文件

package com.yaml;

import com.yaml.entity.Person;
import org.ho.yaml.Yaml;
import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * Hello world!
 */
public class App {

    //写入yaml配置文件
    @Test
    public  void write() {
        /* Initialize data. */
        Person father = new Person();
        father.setName("simon.zhang");
        father.setAge(23);
        father.setSex("man");
        List<Person> children=new ArrayList<Person>();
        for (int i = 8; i < 10; i++) {
            Person child = new Person();
            if (i % 2 == 0) {
                child.setSex("man");
                child.setName("mary" + (i - 7));
            } else {
                child.setSex("fatel");
                child.setName("simon" + (i - 7));
            }
            child.setAge(i);
            children.add(child);
        }
        father.setChildren(children);
        /* Export data to a YAML file. */
        File dumpFile = new File(System.getProperty("user.dir") + "/test/src/main/conf/testYaml.yaml");

        try {
            Yaml.dump(father, dumpFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    //读取yaml配置文件
    @Test
    public  void  read() throws FileNotFoundException {
        File dumpFile=new File(System.getProperty("user.dir") + "/test/src/main/conf/testYaml.yaml");
        Person father = (Person) Yaml.loadType(dumpFile, Person.class);
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(father.getName())
                .append("\t")
                .append(father.getSex())
                .append("\t")
                .append(father.getAge())
                .append("\t")
                .append(father.getChildren().size());
        System.out.println(stringBuilder.toString());

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Map结构的yaml文件
1
JDBC.driver: com.mysql.jdbc.Driver
JDBC.url: "jdbc:mysql://127.0.0.1:3306/shipping_local?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=utf8"
JDBC.username: shipping
JDBC.password: shipping
JDBC.autoCommit: false
1
2
3
4
5
6
读取Map结构

//读取yaml配置文件Map结构
    @Test
    public  void  read2() throws FileNotFoundException {
        File dumpFile=new File(System.getProperty("user.dir") + "/test/src/main/conf/testYaml.yaml");
        Map father =Yaml.loadType(dumpFile, HashMap.class);
        for(Object key:father.keySet()){
            System.out.println(key+":\t"+father.get(key).toString());
        }
    }
1
2
3
4
5
6
7
8
9
打印结果如下:
1

提供 Maven pox.xml 作为参考

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yaml</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jyaml</groupId>
            <artifactId>jyaml</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
--------------------- 
作者:一缕阳光直射你的心扉 
来源:CSDN 
原文:https://blog.csdn.net/u013410747/article/details/51647535 
版权声明:本文为博主原创文章,转载请附上博文链接!

Java读取YAML文件内容包括注释可以通过以下步骤实现: 1. 引入YAML解析库,如jyaml或snakeyaml。 2. 使用YAML解析库读取YAML文件内容。 3. 将读取到的内容存储到一个Map对象中,其中包含键值对和注释。 以下是一个示例代码: ```java import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.reader.StreamReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.*; public class YamlReader { public static void main(String[] args) { Yaml yaml = new Yaml(); try { InputStream stream = new FileInputStream("test.yaml"); Map<String, Object> document = (Map<String, Object>) yaml.load(stream); Map<String, List<String>> comments = extractComments(stream); for (Map.Entry<String, Object> entry : document.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); List<String> commentList = comments.get(key); if (commentList != null) { for (String comment : commentList) { System.out.println(comment); } } System.out.println(key + ": " + value); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private static Map<String, List<String>> extractComments(InputStream stream) { Map<String, List<String>> comments = new HashMap<>(); try { StreamReader reader = new StreamReader(stream); while (reader.hasMore()) { Node node = reader.peekNode(); if (node != null && node.getStartMark().getColumn() == 0 && node.getEndMark().getColumn() == 0) { List<String> commentList = new ArrayList<>(); while (node != null && node.getStartMark().getColumn() == 0 && node.getEndMark().getColumn() == 0) { commentList.add(reader.getNextLine()); node = reader.peekNode(); } comments.put(node.getStartMark().getLine() + "", commentList); } else { reader.getNextLine(); } } } catch (Exception e) { e.printStackTrace(); } return comments; } } ``` 在这个示例中,我们使用了SnakeYAML库来读取YAML文件内容,并使用extractComments方法从文件中提取注释。在主方法中,我们遍历读取到的内容,根据每个键值对的键从注释Map中获取注释,并将注释和值一起输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值