You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开启全字段引号后,如何配置uniVocity CsvWriter为空/Null值去引号

Customizing uniVocity CSVWriter to Skip Quotes for Empty/Null Fields When Using 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 QuoteSelector implementation. This interface lets you define exactly which fields get quoted by returning true or false for 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 CsvWriterSettings to use this custom selector. Even though we set quoteAllFields(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:25:04