← 中文资源

简体中文版本

RFC 4180 CSV 引号转义

按 RFC 4180 编码 CSV 字段:值含逗号、引号或换行时整段加引号,内部引号翻倍转义,写出的行不会被误切割或串列。

阅读英文原文

实现说明

RFC 4180 CSV 引号转义以类 CsvWriter和函数 encodeField、main为骨架。 这个示例中仅有的重复出现在 for (String[] row : rows) 里。

使用要点

  • 运行整个文件:main 会依次驱动 encodeField。

常见问题

「RFC 4180 CSV 引号转义」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

签名一览:static String encodeField(String value)

核心语句

return oneQuote + value.replace(oneQuote, oneQuote + oneQuote) + oneQuote;

代码示例

import java.util.List;

public class CsvWriter {

    // RFC 4180 CSV: quote a field holding comma, quote, or line break; escaping doubles inner quotes
    static String encodeField(String value) {
        boolean needsQuoting = value.indexOf(',') >= 0
                || value.indexOf('"') >= 0
                || value.indexOf('\n') >= 0
                || value.indexOf('\r') >= 0;
        if (!needsQuoting) {
            return value;
        }
        String oneQuote = "" + '"';
        return oneQuote + value.replace(oneQuote, oneQuote + oneQuote) + oneQuote;
    }

    public static void main(String[] args) {
        List<String[]> rows = List.of(
                new String[] {"id", "title", "note"},
                new String[] {"1", "plain", "ok"},
                new String[] {"2", "quoted, value", "comma inside"},
                new String[] {"3", "say " + '"' + "hi" + '"', "quote inside"},
                new String[] {"4", "two\nlines", "newline inside"});

        for (String[] row : rows) {
            StringBuilder line = new StringBuilder();
            for (int i = 0; i < row.length; i++) {
                if (i > 0) {
                    line.append(',');
                }
                line.append(encodeField(row[i]));
            }
            System.out.println(line);
        }
    }
}