InputStream to String in Kotlin BAEL-2654

This commit is contained in:
Alexander Molochko 2019-04-07 00:18:30 +03:00
parent 9578f0de93
commit f6d74e0c86
3 changed files with 62 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package com.baeldung.inputstream
import java.io.InputStream
fun InputStream.readUpToNullChar(nullChar: Char = '\n'): String {
val stringBuilder = StringBuilder()
var currentChar = this.read().toChar()
while (currentChar != nullChar) {
stringBuilder.append(currentChar)
currentChar = this.read().toChar()
if (this.available() <= 0) {
stringBuilder.append(currentChar)
break
}
}
return stringBuilder.toString()
}

View File

@ -0,0 +1,43 @@
package com.baeldung.range
import com.baeldung.inputstream.readUpToNullChar
import kotlinx.io.core.use
import org.junit.Test
import java.io.BufferedReader
import java.io.File
import kotlin.test.assertEquals
class InputStreamToStringTest {
private val fileName = "src/test/resources/inputstream2string.txt"
private val fileFullContent = "Computer programming can be a hassle\r\n" +
"It's like trying to take a defended castle"
private val fileContentUpToNullChar = "Computer programming can be a hassle\r\n" +
"It"
@Test
fun whenReadFileWithBufferedReader_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.bufferedReader().use(BufferedReader::readText)
assertEquals(fileFullContent, content)
}
@Test
fun whenReadFileUpToNullChar_thenPartBeforeNullCharIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.use { it.readUpToNullChar('\'') }
assertEquals(fileContentUpToNullChar, content)
}
@Test
fun whenReadFileWithoutContainingNullChar_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.use { it.readUpToNullChar('-') }
assertEquals(fileFullContent, content)
}
}

View File

@ -0,0 +1,2 @@
Computer programming can be a hassle
It's like trying to take a defended castle