Home > OS >  CSVPrinter adds double quotes at beginning and end of line
CSVPrinter adds double quotes at beginning and end of line

Time:03-04

I'm using CSVPrinter to create a CSV.

@Data
public class ExportRecord {

    String name;
    String email;
    String code;

    @Override
    public String toString() {
        return String.join(";",
                name,
                email,
                StringUtils.defaultString(code));   
    }

}
CSVFormat csvFormat = CSVFormat.EXCEL.builder()
                .setDelimiter(';')
                .setHeader(Arrays.stream(ExportHeader.values()).map(ExportHeader::getCsvHeader).toArray(String[]::new))
                .build();

try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(csvToExport), csvFormat)) {
  for (ExportRecord exportRecord : exportRecords) {
    csvPrinter.printRecord(exportRecord);
  }
} catch (IOException e) {
    ...
}

This is working fine but it adds double quotes to the beginning and the end of the line. e.g.

header1;header2;header3
"string1;string2;string3"

How can I remove those?

CodePudding user response:

I tried an easier solution using PrintWriter and that solved it.

try (PrintWriter printWriter = new PrintWriter(csvToExport)) {
    String header = Arrays.stream(ExportHeader.values())
                    .map(ExportHeader::getCsvHeader)
                    .collect(joining(";"));
    printWriter.println(header);
    for (ExportRecord exportRecord : exportRecords) {
       printWriter.println(exportRecord.toString());
    }
} catch (IOException e) {
    ...
}
  • Related