How to set Jackson ObjectWriter to write to a file line by line in Java

Viewed 17

I am using CsvMapper and am trying to create a txt file from a collection of objects. I also want to do this line by line, so that if an entry fails to be written, I can get the exception message for that specific entry and keep it in another collection. However, instead of being written on a new row, each entry overrides the previous one, so that i always only have 1 entry in the file.

Here is my configuratoin:

CsvMapper mapper = CsvMapper.builder()
                .enable(CsvGenerator.Feature.ALWAYS_QUOTE_EMPTY_STRINGS)
                .enable(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS).build();
        mapper.findAndRegisterModules();
        mapper.setDateFormat(new SimpleDateFormat(StdDateFormat.DATE_FORMAT_STR_ISO8601));

final CsvSchema schema = mapper.schemaFor(UserRow.class).withHeader().withNullValue("\"\"")
                .withColumnSeparator(GlobalConfig.getInstance().getFileDelimiter())
                .withQuoteChar('\"');
        final ObjectWriter objectWriter = mapper.writer(schema);

for (UserRow row : rows) {
            try {
                objectWriter.writeValueAsString(file, row));
            } catch (IOException e) {
                ...;
            }
        }

Any suggestions are appreciated!

0 Answers
Related