Supercsv Append Rather Than Overwrite?
Is it possible to add new lines to a CSV file, rather than overwrite the last one? Here is my method I call when I want to add a new line: private static void writeWithCsvMapWriter
Solution 1:
Add true
to the parameters in new FileWriter
:
mapWriter = new CsvMapWriter(new FileWriter(".../writeWithCsvMapWriter.csv", true), CsvPreference.STANDARD_PREFERENCE);
Solution 2:
As frickskit pointed out: the trick is to add true
as the second parameter of new FileWriter()
, but this will add the header underneath existing rows again as well. Use something in the lines of the following to check for the existence of a header in an existing file first before you decide to write it out.
publicvoidwrite(String fileName, List<Map<String, String>> lines)throws IOException {
final String[] HEADER = newString[] {
"Column1",
"Column2",
"Column3"
};
booleanwriteHeader=true;
try (ICsvMapReadermapReader=newCsvMapReader(newFileReader(fileName), CsvPreference.STANDARD_PREFERENCE)) {
final String[] existingHeader = mapReader.getHeader(true);
if (Arrays.equals(existingHeader, HEADER)) {
writeHeader = false;
}
} catch (FileNotFoundException ex) {}
try (ICsvMapWritermapWriter=newCsvMapWriter(newFileWriter(fileName, true), CsvPreference.STANDARD_PREFERENCE)) {
final CellProcessor[] processors = getProcessors();
if (writeHeader) {
mapWriter.writeHeader(HEADER);
}
for (Map<String, String> entry : lines) {
mapWriter.write(entry, HEADER, processors);
}
}
}
Post a Comment for "Supercsv Append Rather Than Overwrite?"