Skip to content

Commit

Permalink
fix write csv escape comma & line separator
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Dec 10, 2024
1 parent 0330cab commit 69acc7b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public void writeString(final String str) {
char ch = str.charAt(i);
if (ch == ',') {
comma = true;
} else if (ch == '"') {
} else if (ch == '"' || ch == '\n' || ch == '\r') {
escapeCount++;
}
}
Expand All @@ -123,7 +123,7 @@ public void writeString(final String str) {
}
}

if (escapeCount == 0) {
if (escapeCount == 0 && !comma) {
if (len + off >= chars.length) {
flush();
if (len > chars.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public void writeString(byte[] utf8) {
for (byte ch : utf8) {
if (ch == ',') {
comma = true;
} else if (ch == '"') {
} else if (ch == '"' || ch == '\n' || ch == '\r') {
escapeCount++;
}
}
Expand All @@ -169,7 +169,7 @@ public void writeString(byte[] utf8) {
}
}

if (escapeCount == 0) {
if (escapeCount == 0 && !comma) {
writeRaw(utf8);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,22 @@ public void test6UTF8() throws Exception {
}
}

@Test
public void test7() throws Exception {
try (CSVWriter csvWriter = CSVWriter.of(new StringWriter())) {
csvWriter.writeString(",abc".getBytes());
assertEquals("\",abc\"", csvWriter.toString());
}
}

@Test
public void test7UTF8() throws Exception {
try (CSVWriter csvWriter = CSVWriter.of(new ByteArrayOutputStream())) {
csvWriter.writeString(",abc".getBytes());
assertEquals("\",abc\"", csvWriter.toString());
}
}

@Test
public void testWriteInstant() throws Exception {
LocalDate date = LocalDate.of(2018, 7, 12);
Expand Down

0 comments on commit 69acc7b

Please sign in to comment.