Merge pull request #6674 from CROSP/inputstream-to-string-in-kotlin

BAEL-2654 InputStream to String in Kotlin
This commit is contained in:
Eric Martin 2019-04-13 20:21:52 -05:00 committed by GitHub
commit 7fc7e61674
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 91 additions and 0 deletions

View File

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

View File

@ -0,0 +1,71 @@
package com.baeldung.inputstream
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"
@Test
fun whenReadFileWithBufferedReader_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.bufferedReader().use(BufferedReader::readText)
assertEquals(fileFullContent, content)
}
@Test
fun whenReadFileWithBufferedReaderReadText_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val reader = BufferedReader(inputStream.reader())
var content: String
try {
content = reader.readText()
} finally {
reader.close()
}
assertEquals(fileFullContent, content)
}
@Test
fun whenReadFileWithBufferedReaderManually_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val reader = BufferedReader(inputStream.reader())
val content = StringBuilder()
try {
var line = reader.readLine()
while (line != null) {
content.append(line)
line = reader.readLine()
}
} finally {
reader.close()
}
assertEquals(fileFullContent.replace("\r\n", ""), content.toString())
}
@Test
fun whenReadFileUpToStopChar_thenPartBeforeStopCharIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.use { it.readUpToChar(' ') }
assertEquals("Computer", content)
}
@Test
fun whenReadFileWithoutContainingStopChar_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.use { it.readUpToChar('-') }
assertEquals(fileFullContent, content)
}
}

View File

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