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.
Code
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
Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.