javaspringcsvapache-camelopencsv

How to have double quotes only on embedded comma String in csv using CSVWriter?


This is my expected result format in the output csv:

header1,header2,header3,header4
monica,chandler,"rachel,ross",joey

My current results:

Strategy1:

CSVWriter csvWriter = new CSVWriter(new FileWriter("D:/new.csv"));
String[] headers = new String[] { "header1", "header2", "header3", "header4"};    
String[] arr = new String[] { "monica", "chandler", "rachel,ross", "joey"};


result:
"header1","header2","header2","header4"
"monica","chandler","rachel,ross","joey"

Strategy2:

CSVWriter csvWriter = new CSVWriter(new FileWriter("D:/new.csv"), CSVWriter.DEFAULT_SEPARATOR,CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
    String[] headers = new String[] { "header1", "header2", "header3", "header4"};    
    String[] arr = new String[] { "monica", "chandler", "rachel,ross", "joey"};


result:
header1,header2,header2,header4
monica,chandler,rachel",ross,joey

Can anyone suggest to me how to achieve this using OpenCSV framework's CSVWriter?


Solution

  • You can use the CsvWriter::writeNext method which also takes a boolean to indicate whether to use quotes always, or only when needed.

    From the documentation:

    applyQuotesToAll - True if all values are to be quoted. False applies quotes only to values which contain the separator, escape, quote, or new line characters.

    An example:

    try (CSVWriter csvWriter = new CSVWriter(new FileWriter("new.csv"))) {
        String[] headers = new String[]{"header1", "header2", "header3", "header4"};
        String[] arr = new String[]{"monica", "chandler", "rachel,ross", "joey"};
        csvWriter.writeNext(headers, false);
        csvWriter.writeNext(arr, false);
    }
    

    The results:

    header1,header2,header3,header4
    monica,chandler,"rachel,ross",joey