Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-14089

This commit is contained in:
amit2103 2019-04-14 11:17:05 +05:30
commit 2dd7251361
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