Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/main/java/org/apache/commons/csv/CSVFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -815,8 +815,11 @@ public Builder setQuote(final Character quoteCharacter) {
}

private Builder setQuotedNullString() {
final Character quote = quoteCharacter != null ? quoteCharacter : Constants.DOUBLE_QUOTE_CHAR;
this.quotedNullString = quote + nullString + quote;
final char quote = quoteCharacter != null ? quoteCharacter.charValue() : Constants.DOUBLE_QUOTE_CHAR.charValue();
// Double the quote character inside the null marker, otherwise the quoted marker closes its own
// encapsulation and the emitted token is invalid or spans several fields.
final String marker = nullString != null ? nullString : "null";
this.quotedNullString = quote + marker.replace(String.valueOf(quote), String.valueOf(quote) + quote) + quote;
return this;
}

Expand Down
17 changes: 17 additions & 0 deletions src/test/java/org/apache/commons/csv/CSVPrinterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2291,6 +2291,23 @@ void testTrimOnTwoColumns() throws IOException {
assertEquals("A,B", sw.toString());
}
}
@Test
void testQuotedNullStringEscapesEmbeddedQuoteCharacter() throws IOException {
// QuoteMode.ALL writes null as the quoted null marker. The marker must escape its own quote characters,
// otherwise it closes its encapsulation early and the printer emits CSV the parser rejects.
final CSVFormat format = CSVFormat.DEFAULT.builder().setNullString("N\"A").setQuoteMode(QuoteMode.ALL).get();
final StringWriter sw = new StringWriter();
try (CSVPrinter printer = new CSVPrinter(sw, format)) {
printer.printRecord("x", null);
}
assertEquals("\"x\",\"N\"\"A\"" + RECORD_SEPARATOR, sw.toString());
try (CSVParser parser = CSVParser.parse(sw.toString(), format)) {
final CSVRecord record = parser.getRecords().get(0);
assertEquals(2, record.size());
assertEquals("x", record.get(0));
assertNull(record.get(1));
}
}

private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException {
try (CSVParser parser = CSVParser.parse(expected, format)) {
Expand Down