Skip to content

Commit 2922f92

Browse files
committed
fix NPE when null present in output Seq
1 parent 4de875b commit 2922f92

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/main/scala/com/github/tototoshi/csv/CSVWriter.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ class CSVWriter (protected val writer: Writer)(implicit val format: CSVFormat) {
5959
def escapeDelimiterChar(field: String): String =
6060
field.replace(format.delimiter.toString, format.escapeChar.toString + format.delimiter.toString)
6161

62-
def show(s: Any): String = s.toString
62+
def show(s: Any): String = Option(s).getOrElse("").toString
6363

6464
val renderField = {
6565
val escape = format.quoting match {

src/test/scala/com/github/tototoshi/csv/CSVWriterSpec.scala

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,19 @@ class CSVWriterSpec extends FunSpec with ShouldMatchers with BeforeAndAfter with
7979

8080
readFileAsString("test.csv") should be (expected)
8181
}
82+
83+
it("writes null fields as empty strings") {
84+
using (CSVWriter.open(new FileWriter("test.csv"))) { writer =>
85+
writer.writeAll(List(List("a", null, "c"), List("d", "e", null)))
86+
}
87+
88+
val expected = """|a,,c
89+
|d,e,
90+
|""".stripMargin
91+
92+
readFileAsString("test.csv") should be (expected)
93+
}
94+
8295
describe ("When stream is already closed") {
8396
it ("throws an Exception") {
8497
val writer = CSVWriter.open("test.csv")
@@ -103,6 +116,18 @@ class CSVWriterSpec extends FunSpec with ShouldMatchers with BeforeAndAfter with
103116

104117
readFileAsString("test.csv") should be (expected)
105118
}
119+
it("write single line with null fieldsto file") {
120+
using (CSVWriter.open(new FileWriter("test.csv"))) { writer =>
121+
writer.writeRow(List("a", null, "c"))
122+
writer.writeRow(List("d", "e", null))
123+
}
124+
125+
val expected = """|a,,c
126+
|d,e,
127+
|""".stripMargin
128+
129+
readFileAsString("test.csv") should be (expected)
130+
}
106131
describe ("When a field contains quoteChar in it") {
107132
it ("should escape the quoteChar") {
108133
using (CSVWriter.open(new FileWriter("test.csv"))) { writer =>

0 commit comments

Comments
 (0)