RFC 4180 CSV Quote Escaping

Encode one CSV field per RFC 4180: quote when the value holds a comma, quote, or line break, and double embedded quotes when escaping.

JavaData Integrity

Code

snippet
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);
        }
    }
}

How it works

RFC 4180 CSV Quote Escaping comes down to the class CsvWriter and the functions encodeField and main.

The file repeats itself only inside for (String[] row : rows).

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The primary signature is static String encodeField(String value)

There are 1 call inside main — encodeField — executed top to bottom.

Key statements worth quoting

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

Interactive Tools for This Topic

FAQ

How do you run RFC 4180 CSV Quote Escaping?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.