Search code examples
javafile-ioyamlsnakeyaml

How to dump Yaml object into File?


I have a simple java program which is using snakeyaml to read the yaml file and I have edited some values of yaml object. But I am unable to dump the object back to yaml file. Not sure whats the right way to dumping the yaml object to file.

Heres the code

       InputStream input = new FileInputStream(new File("/etc/cassandra/cassandra.yaml")); 
        Writer output = null;
        try {
            output = new FileWriter("/etc/cassandra/cassandra.yaml");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Yaml yaml = new Yaml();
        Map<String, Object> data = (Map<String, Object>) yaml.load(input);
        System.out.println("yaml data is " +data.get("saved_caches_directory"));
        data.put("saved_caches_directory", "/var/lib/cassandra/saved_new_caches");
        yaml.dump(data, output);
        System.out.println(output.toString());
        output.write(data);  // Error in this line.

    }

I need the yaml.dump() to dump the modified yaml object back to the file. I am not sure how the write happens in there. According to eclipse yaml.dump(data, output); method is availabe where output is writer object. I am not sure how to instantiate the write object to send it back to file.


Solution

  • To create a Writer

    Writer writer = new FileWriter("/etc/cassandra/cassandra.yaml");
    

    To dump the data to the writer

    yaml.dump(data, writer);
    

    To close the writer when you are finished

    writer.close();