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

Java/OpenCSV写入CSV时如何转义换行符并导出UTF-8文件

问题解决指南

1. 保留字段内换行符,避免生成新记录

CSV规范明确要求:包含换行符、逗号等特殊字符的字段必须用引号包裹,否则会被解析为新行或字段分隔符。你的代码中设置了withQuotechar(CSVWriter.NO_QUOTE_CHARACTER),这是导致带换行符的字段被拆分成新记录的核心原因。

修正配置要点:

  • 移除withQuotechar(CSVWriter.NO_QUOTE_CHARACTER),使用OpenCSV默认的双引号作为字段包裹符
  • 无需设置withEscapechar('\n'),OpenCSV会自动处理字段内的换行符,只要字段被引号包裹
  • 保留withApplyQuotesToAll(true)可确保所有字段都被引号包裹,避免其他特殊字符引发格式问题

2. 导出UTF-8编码文件

Files.newBufferedWriter默认编码依赖系统环境,要明确生成UTF-8编码文件,需在创建Writer时指定StandardCharsets.UTF_8参数。

修改后的完整代码

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;

public class CsvWriterHandler {
    public void writeShopifyCsv(File outDirectory, String outputCSVName, Iterable<Shopify> data) {
        File file = new File(outDirectory, outputCSVName);

        try (Writer writer = Files.newBufferedWriter(Paths.get(file.toURI()), StandardCharsets.UTF_8)) {
            StatefulBeanToCsv<Shopify> beanToCsv = new StatefulBeanToCsvBuilder<Shopify>(writer)
                    .withApplyQuotesToAll(true)
                    .withLineEnd("\n")
                    .withSeparator(',')
                    .build();

            beanToCsv.write(data);
            // try-with-resources语法会自动关闭Writer,无需手动调用close()
        } catch (CsvRequiredFieldEmptyException | IOException e) {
            throw new RuntimeException(e);
        } catch (CsvDataTypeMismatchException e) {
            throw new RuntimeException(e);
        }
    }
}

关键说明

  • 引号包裹:通过双引号包裹字段后,CSV解析器会将字段内的换行符视为字段内容的一部分,不会拆分记录
  • UTF-8编码:明确指定编码参数,确保文件以UTF-8格式保存,避免乱码
  • 资源自动管理:try-with-resources会自动释放Writer资源,避免手动关闭引发的异常

内容的提问来源于stack exchange,提问作者tmzafar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:38:29