1

EDIT: I've tried overriding the method as proposed, but it adds a white line

I'm using OpenCSV to read/write from a CSV file, and I need to append a new row of my object "Crime" when a user adds another one.
Until now, I've only found this way of writing in all tutorials:

 Writer writer  = new FileWriter(path.toString());

StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer)
   .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
   .build();

List<CsvBean> list = new ArrayList<>();
list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd"));
list.add(new WriteExampleBean("Test2", "ipso", "facto"));

sbc.write(list);
writer.close();

The problem is that before adding the new row, it also adds the header, so my file becomes:

zipCode,totPopulation,medianAge,totMales,totFemales,totHouseholds,avgHouseholdSize,
91371,1,73.5,0,1,1,1,
90001,57110,26.6,28468,28642,12971,4.4,
90002,51223,25.5,24876,26347,11731,4.36,
90003,66266,26.3,32631,33635,15642,4.22,
zipCode,totPopulation,medianAge,totMales,totFemales,totHouseholds,avgHouseholdSize,
100,100,100,100,100,100,100

where the line with all "100" values is the one I add. How can I prevent to add the header before the line every time I want to add a row or multiple rows?

Usr
  • 2,628
  • 10
  • 51
  • 91
  • 2
    Possible duplicate of [Appending to CSV file without headers](https://stackoverflow.com/questions/48922642/appending-to-csv-file-without-headers) – Arnaud Mar 25 '19 at 14:10
  • 1
    @Arnaud overriding the method adds an empty line – Usr Mar 25 '19 at 15:45

1 Answers1

0

Try to extend the HeaderColumnNameMappingStrategy and override the method generateHeader to return an empty array.

Then pass an instance of your new class to the StatefulBeanToCsvBuilder through withMappingStrategy()

According to the Javadoc of MappingStrategy:

If no header can or should be generated, an array of zero length must be returned, and not null.

Make sure you only do this if the file is not new if you want to include the headers in the first line.

jbx
  • 21,365
  • 18
  • 90
  • 144