diff --git a/src/jvmMain/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriter.kt b/src/jvmMain/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriter.kt index b9645b9..97eab7b 100644 --- a/src/jvmMain/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriter.kt +++ b/src/jvmMain/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriter.kt @@ -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). @@ -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 *** * @@ -133,4 +140,11 @@ actual class CsvWriter actual constructor( suspend fun writeAllAsync(rows: List>, ops: OutputStream) { open(ops) { writeRows(rows) } } + + /** + * write all rows to string + */ + fun writeAll(rows: List>): String { + return writeString { writeRows(rows) } + } } diff --git a/src/jvmTest/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriterTest.kt b/src/jvmTest/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriterTest.kt index 72b86a6..fb70c66 100644 --- a/src/jvmTest/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriterTest.kt +++ b/src/jvmTest/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvWriterTest.kt @@ -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" @@ -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 {