diff --git a/theodolite/src/main/kotlin/rocks/theodolite/core/IOHandler.kt b/theodolite/src/main/kotlin/rocks/theodolite/core/IOHandler.kt index 8721ea9d4314fb6a914ab678575c5e4b7c5f90ad..78b353a1e525984575e63830ee16b5c60f02c3ae 100644 --- a/theodolite/src/main/kotlin/rocks/theodolite/core/IOHandler.kt +++ b/theodolite/src/main/kotlin/rocks/theodolite/core/IOHandler.kt @@ -71,21 +71,32 @@ class IOHandler { fun writeToCSVFile(fileURL: String, data: List<List<String>>, columns: List<String>) { val outputFile = File("$fileURL.csv") PrintWriter(outputFile).use { pw -> - pw.println(columns.joinToString(separator = ",")) + + val writeColumns = addQuotationMarks(columns) + pw.println(writeColumns.joinToString(separator = ",")) + data.forEach{ row -> - val writeRow = row.toMutableList() - // change entry if it contains a comma - writeRow.forEachIndexed { index, entry -> - if (entry.contains(",")){ - writeRow[index] = "\"" + entry + "\"" - } - } + val writeRow = addQuotationMarks(row) pw.println(writeRow.joinToString(separator = ",")) } } logger.info { "Wrote CSV file: $fileURL to ${outputFile.absolutePath}." } } + /** + * For a list of Strings: + * Adds quotation marks around strings that contain a comma + */ + private fun addQuotationMarks(stringList: List<String> ): List<String> { + val stringMutableList = stringList.toMutableList() + stringMutableList.forEachIndexed { index, entry -> + if (entry.contains(",")){ + stringMutableList[index] = "\"" + entry + "\"" + } + } + return stringMutableList + } + /** * Write to text file * diff --git a/theodolite/src/test/kotlin/rocks/theodolite/core/IOHandlerTest.kt b/theodolite/src/test/kotlin/rocks/theodolite/core/IOHandlerTest.kt index acdf3aa6efe1060a0123f4bfb2b27eba312f8305..938eeaa7a3c8f14bdebf8d3d341bc5b209e3f44d 100644 --- a/theodolite/src/test/kotlin/rocks/theodolite/core/IOHandlerTest.kt +++ b/theodolite/src/test/kotlin/rocks/theodolite/core/IOHandlerTest.kt @@ -43,12 +43,13 @@ internal class IOHandlerTest { temporaryFolder.create() val folder = temporaryFolder.newFolder(FOLDER_URL) + val columns = listOf("Fruit", "Color") + val testContent = listOf( listOf("apples", "red"), listOf("bananas", "yellow"), listOf("avocado", "brown") ) - val columns = listOf("Fruit", "Color") IOHandler().writeToCSVFile( fileURL = "${folder.absolutePath}/test-file", @@ -74,7 +75,8 @@ internal class IOHandlerTest { temporaryFolder.create() val folder = temporaryFolder.newFolder(FOLDER_URL) - val columns = listOf("Fruit", "Color") + val columns = listOf("Fruit, Fruit2", "Color") + val expectedColumns = listOf("\"Fruit, Fruit2\"", "Color") val testContent = listOf( listOf("apples, paprika", "red"), @@ -95,7 +97,7 @@ internal class IOHandlerTest { ) // construct string from the columns - var expected = columns.stream().collect(Collectors.joining(",")) + var expected = expectedColumns.stream().collect(Collectors.joining(",")) // add values from the expectedContent to expected string expectedContent.forEach{