@[toc]

preface

Yaml itself is a markup language in the form of.yML files, which are often used for data configuration

The following Yaml comes from the dependency package org.yaml. Snakeyaml and needs to be imported by yourself

Java read yaml

@Test
    public void read(a) throws IOException {
        Yaml yml = new Yaml();
        FileReader reader = new FileReader("src\\test\\java\\test.yml");
        BufferedReader buffer = new BufferedReader(reader);
        Map<String,Object> map = yml.load(buffer);
        System.out.println(map.get("key1"));
        System.out.println(map.get("key2"));
        buffer.close();
        reader.close();
    }
Copy the code

Java write yaml

@Test
    public void write(a) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("key1".1);
        map.put("key2"."2");
        Yaml yml = new Yaml();
        FileWriter writer = new FileWriter("src\\test\\java\\test.yml".true);
        BufferedWriter buffer = new BufferedWriter(writer);
        buffer.newLine();
        yml.dump(map, buffer);
        buffer.close();
        writer.close();
    }
Copy the code

What’s notable here is the dump() method, which essentially dumps data, converting key-value pairs to strings

Dump can accept one argument, or two arguments. If you receive two arguments, the second argument is the output stream. Returns a String when an argument is received, so that the output stream’s write() method can be written directly to YML; Return void when two arguments are received to write directly to disk.

There is a difference between dump() writing directly to disk and write() writing directly to disk. Dump () automatically adds a carriage return after writing, whereas write() does not