Amna Irshad Sipra
Amna Irshad Sipra

Reputation: 136

Appending data to existing CSV using Jackson CSV

How Can I append the data to existing CSV File using Jackson CSV (https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv) Here is my code

public synchronized Boolean AppendToFile(Path fullFilePath, InputDataFormat obj) throws IOException {
    if (mapper == null || schema == null)
        init();

    File outputFile = new File(fullFilePath.toUri());
    if (!outputFile.exists()) {
        outputFile.createNewFile();
    }

    ObjectWriter writer  = mapper.writer(schema);
    mapper.writer(schema).writeValue(outputFile, obj);

    return true;
}

It writes to the file but does not retain the existing data

Upvotes: 2

Views: 3880

Answers (1)

Amna Irshad Sipra
Amna Irshad Sipra

Reputation: 136

Resolved using OutputStream and passing append flag as true

 public Boolean AppendToFile(Path fullFilePath, Account obj) {
    logger.info(" Acquired Write lock on file " + fullFilePath.getFileName());

    mapper = new CsvMapper();
    mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
    schema = mapper.schemaFor(Account.class).withColumnSeparator('|');


        File outputFile = new File(fullFilePath.toUri());
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }
        ObjectWriter writer = mapper.writer(schema);
        OutputStream outstream = new FileOutputStream(outputFile , true);
        writer.writeValue(outstream,obj);
  return true;
}

Upvotes: 4

Related Questions