0

I want to append from time to time entities in a yaml file, like logging actions, as they arrive. Something like this

    item:
        entityType: article
        entityId: 318 
        created: 1655282744819 
        user: "admin"
        title: "Morning" 
        eventType: "viewing"

    item:
        entityType: event
        entityId: 339 
        created: 1655223444821 
        user: "admin"
        title: "Evening" 
        eventType: "editing"

But I face with the situation when I can write yaml to a new file only.

objectMapper.writeValue(new File(path), logItem);

Is there any possibilities to append data to existing file? Thanks in advance.

LadyBug
  • 71
  • 8

1 Answers1

1

You load the YAML, put your new data into the parsed data, and then serialize the whole data again to the file it came from.

You can't simply append to a YAML file because a YAML file represents a directed graph of nodes, and there's no meaningful definition of append on a graph of nodes. There is a definition of append on a stream of characters, sure, but what you want to do is to modify the data this stream represents, which is the graph of nodes. Simply concatenating two character streams, where each is a valid YAML document, does not necessarily produce a valid YAML document.

You can, if you're really dedicated, use the low-level API which emits parsing events, inject your new structure as events into that event stream, and present it again (transform it back to a character stream). This answer shows how this works in PyYAML, it's not possible with Jackson because that API is too high level but you could do it with SnakeYAML if you want to stick to Java. SnakeYAML's low-level API is quite similar to PyYAML. However be aware that this endeavour is likely not what you actually want to do since you can't give your logItem as class instance, you need to give it as sequence of events.

flyx
  • 35,506
  • 7
  • 89
  • 126