Skip to content

Commit

Permalink
Add utility functions to write to String (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
Thijsiez authored Aug 7, 2022
1 parent e4f8019 commit dbcfd46
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.github.doyaaaaaken.kotlincsv.dsl.context.ICsvWriterContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.*
import java.nio.charset.Charset

/**
* CSV Writer class, which decides where to write and returns CsvFileWriter class (class for controlling File I/O).
Expand Down Expand Up @@ -50,6 +51,12 @@ actual class CsvWriter actual constructor(
writer.use { it.write() }
}

fun writeString(write: ICsvFileWriter.() -> Unit): String {
val baos = ByteArrayOutputStream()
open(baos, write)
return String(baos.toByteArray(), Charset.forName(ctx.charset))
}

/**
* *** ONLY for long-running write case ***
*
Expand Down Expand Up @@ -133,4 +140,11 @@ actual class CsvWriter actual constructor(
suspend fun writeAllAsync(rows: List<List<Any?>>, ops: OutputStream) {
open(ops) { writeRows(rows) }
}

/**
* write all rows to string
*/
fun writeAll(rows: List<List<Any?>>): String {
return writeString { writeRows(rows) }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,20 @@ class CsvWriterTest : WordSpec({
}
}

"writeString method" should {
val row1 = listOf("a", "b", null)
val row2 = listOf("d", "2", "1.0")
val expected = "a,b,\r\nd,2,1.0\r\n"

"write simple csv data to String" {
val actual = csvWriter().writeString {
writeRow(row1)
writeRow(row2)
}
actual shouldBe expected
}
}

"writeAll method without calling `open` method" should {
val rows = listOf(listOf("a", "b", "c"), listOf("d", "e", "f"))
val expected = "a,b,c\r\nd,e,f\r\n"
Expand All @@ -112,6 +126,11 @@ class CsvWriterTest : WordSpec({
val actual = readTestFile()
actual shouldBe expected
}

"write data to String" {
val actual = csvWriter().writeAll(rows)
actual shouldBe expected
}
}

"Customized CsvWriter" should {
Expand Down

0 comments on commit dbcfd46

Please sign in to comment.