开启全字段引号后,如何配置uniVocity CsvWriter为空/Null值去引号
quoteAllFields(true) Got it, I’ve dealt with this exact requirement before when working with uniVocity’s CSVWriter. The default behavior of settings.setQuoteAllFields(true) wraps every single field—including null values and empty strings—in quotes, which isn’t what you’re aiming for here. Thankfully, there’s a straightforward way to tweak the quoting logic to only wrap non-empty, non-null fields while keeping your global quote setting context.
Here’s how to make it work:
- First, create a custom
QuoteSelectorimplementation. This interface lets you define exactly which fields get quoted by returningtrueorfalsefor each value:
QuoteSelector customQuoteSelector = new QuoteSelector() { @Override public boolean shouldQuote(FieldWriter writer, String value) { // Only quote fields that are non-null and not empty strings return value != null && !value.isEmpty(); } };
- Next, configure your
CsvWriterSettingsto use this custom selector. Even though we setquoteAllFields(true), the custom selector will override this decision on a per-field basis:
CsvWriterSettings settings = new CsvWriterSettings(); settings.setQuoteAllFields(true); // Assign our custom quote selector settings.setQuoteSelector(customQuoteSelector); // If you need semicolons as separators (matching your example output), add this line: settings.setSeparator(';'); CsvWriter writer = new CsvWriter(new StringWriter(), settings); String stringRow = writer.writeRowToString(new String[] {null, "", "", "123"}); // The output will be: ;;;"123"
This works because the QuoteSelector takes precedence over the global quoteAllFields setting. Every time the writer processes a field, it checks this selector to decide whether to wrap the value in quotes. For null or empty values, it returns false, so no quotes are added—exactly the behavior you’re looking for.
内容的提问来源于stack exchange,提问作者Bestows In Constructing

