Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #97: Write directly to a String #107

Merged
merged 1 commit into from
Aug 7, 2022
Merged
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
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