Java读取/写入Yaml配置文件

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

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

age: 23
children: 
  - 
    age: 8
    name: mary1
    sex: man
  - 
    age: 9
    name: simon2
    sex: fatel
name: simon.zhang
sex: man

 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.....
}

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());

    }
}

Map结构的yaml文件

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

读取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());
        }
    }

打印结果如下:

提供 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>

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: YAMLYAML Ain't Markup Language)是一种用于序列化数据的格式,它采用简洁易读的文本形式,常用于配置文件和数据交换。在Java中,可以使用第三方库进行YAML文件的读取写入。 要读取YAML文件,首先需要引入相关的库,比如SnakeYAML。然后创建一个Yaml对象,并使用其load方法来加载YAML文件。加载完成后,我们可以通过Yaml对象的get方法获取YAML文件中的数据。例如: ```java import org.yaml.snakeyaml.Yaml; import java.io.FileInputStream; import java.io.FileNotFoundException; public class YAMLReader { public static void main(String[] args) { try { Yaml yaml = new Yaml(); FileInputStream inputStream = new FileInputStream("config.yaml"); // 加载YAML文件 Object data = yaml.load(inputStream); // 获取YAML文件中的数据 System.out.println(data.toString()); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } ``` 要写入YAML文件,同样需要引入相关的库,然后创建一个Yaml对象,并使用其dump方法来将数据写入YAML文件。例如: ```java import org.yaml.snakeyaml.Yaml; import java.io.FileWriter; import java.io.IOException; public class YAMLWriter { public static void main(String[] args) { Yaml yaml = new Yaml(); try { FileWriter writer = new FileWriter("config.yaml"); // 数据写入YAML文件 yaml.dump(data, writer); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在写入YAML文件时,需要将要写入的数据传递给dump方法,并指定要写入的目标文件。完成写入后,通过关闭文件流来确保数据写入完成。 总之,通过使用第三方库,Java可以方便地读取写入YAML文件,实现数据的序列化和反序列化。 ### 回答2: YAML是一种轻量级的数据序列化格式,它以易读易写的方式表示数据,并且支持多种数据类型。在Java中,我们可以使用一些第三方库来读取写入YAML文件。 要读取YAML文件,可以使用例如SnakeYAML和Jackson YAML这样的库。首先,我们需要添加相应的依赖项到项目中。接下来,可以使用流式API或对象映射API来读取YAML文件。 使用流式API,我们可以按序解析YAML文件中的数据,如下所示: ```java InputStream inputStream = new FileInputStream("file.yaml"); Yaml yaml = new Yaml(); Map<String, Object> data = yaml.load(inputStream); ``` 使用对象映射API,我们可以将YAML文件中的数据映射为Java对象,如下所示: ```java InputStream inputStream = new FileInputStream("file.yaml"); Yaml yaml = new Yaml(new Constructor(YourClass.class)); YourClass obj = yaml.load(inputStream); ``` 要写入YAML文件,我们可以使用与读取相同的库和API。下面是一个示例: ```java YourClass obj = new YourClass(); Yaml yaml = new Yaml(); String output = yaml.dump(obj); Files.write(Paths.get("file.yaml"), output.getBytes()); ``` 在这个示例中,我们首先创建了一个YourClass对象,然后使用Yaml库将其转换为YAML字符串。最后,我们将YAML字符串写入文件。 总结来说,要在Java读取写入YAML文件,我们可以选择使用SnakeYAML或Jackson YAML这样的第三方库。使用这些库,我们可以使用流式API或对象映射API来读取写入YAML文件。 ### 回答3: 在Java中,我们可以使用不同的库来读取写入YAML文件。 要读取YAML文件,我们可以使用 Jackson 或 SnakeYAML 等库。这些库可将YAML文件解析为Java对象,以便我们可以访问和操作其中的数据。 使用 Jackson库时,我们需要添加 jackson-databind 和 jackson-dataformat-yaml 依赖项。下面是一个示例代码,展示了如何读取YAML文件并解析为Java对象: ```java import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; public class YamlReader { public static void main(String[] args) { try { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); File file = new File("example.yaml"); MyObject myObject = objectMapper.readValue(file, MyObject.class); System.out.println(myObject); } catch (Exception e) { e.printStackTrace(); } } } ``` 对于写入YAML文件,我们可以使用与读取类似的方式,先创建一个Java对象,然后使用 Jackson 或 SnakeYAML 来将其转换为YAML格式,并将其写入文件。 使用 Jackson库时,我们可以使用 writeValue() 方法将Java对象写入YAML文件,示例如下: ```java import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; public class YamlWriter { public static void main(String[] args) { try { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); MyObject myObject = new MyObject(); // 设置对象属性 File file = new File("example.yaml"); objectMapper.writeValue(file, myObject); } catch (Exception e) { e.printStackTrace(); } } } ``` 总之,无论是读取还是写入YAML文件,我们都可以使用不同的库来实现。在Java中,Jackson 和 SnakeYAML 是常用的选择,它们提供了简单且强大的功能来处理YAML文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值