ppb
ppb

Reputation: 2633

Delete existing row from CSV file and create new one in Jackson

I am using Jackson to read and write to CSV file. I am writing a API which accepts a JSON request and write the java object into CSV file which is working fine, but I am not sure how to check in csv file that given data or java object is already present. I need to check that data is present so delete that entire row and add new data which coming from API.

e.g. I have below CSV file data -

id,name,gender,action
 1,abc,male,add
 2,def,male,delete

My Rest API is below to -

@PostMapping(path= "/config", consumes = "application/json", produces = "application/json")
public ResponseEntity<String> updateConfig(@RequestBody List<EmpData> configs){
    File file = new File(CONFIG_FILE);
    Util.addOrUpdate(file, configs);
    return ResponseEntity.ok("SUCCESS");
}


 public static void addOrUpdate(File file, List<EmpData> data) {
    
    CsvMapper mapper = new CsvMapper();
    mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
    CsvSchema schema = mapper.schemaFor(EmpData.class)
            .withColumnSeparator(',');

    File outputFile = new File(file.toURI());
    try {
      
        ObjectWriter writer = mapper.writerFor(EmpData.class).with(schema);
        OutputStream os = new FileOutputStream(outputFile , true);
        writer.writeValues(os).writeAll(data);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Above code is working fine for adding new row in a csv file, but how can I delete existing row if present and add new one.

I want to compare with id, if given id in REST API body is present in csv file then delete it from csv and create new record with that id from REST API body.

Upvotes: 0

Views: 144

Answers (1)

Yury
Yury

Reputation: 99

You can do something like described here Find a line in a file and remove it. If your csv always starts with id, you can easily filter it out.

Upvotes: -1

Related Questions