javacsvsupercsv

How to configure Super CSV to quote all values except column names?


Requirements are:

For example

Name, Age, Location
"A","154","California"
"B","2","New York"

How do I create such SuperCSV Preference for writing?


Solution

  • Use following Custom Quote Mode:

    public class AllExceptHeaderQuoteMode implements QuoteMode {
    
        @Override
        public boolean quotesRequired(String csvColumn, CsvContext context, CsvPreference preference) {
            if (1 == context.getLineNumber()) {
                /*
                 * Case whene column names are written
                 */
                return false;
            } else {
                return true;
            }
        }
    }
    

    Using Custom Quote Mode:

    CsvPreference preference = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).useQuoteMode(new AllExceptHeaderQuoteMode()).build());