Skip to content

Commit f6d74e0

Browse files
committed
InputStream to String in Kotlin BAEL-2654
1 parent 9578f0d commit f6d74e0

3 files changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.inputstream
2+
3+
import java.io.InputStream
4+
5+
fun InputStream.readUpToNullChar(nullChar: Char = '\n'): String {
6+
val stringBuilder = StringBuilder()
7+
var currentChar = this.read().toChar()
8+
while (currentChar != nullChar) {
9+
stringBuilder.append(currentChar)
10+
currentChar = this.read().toChar()
11+
if (this.available() <= 0) {
12+
stringBuilder.append(currentChar)
13+
break
14+
}
15+
}
16+
return stringBuilder.toString()
17+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.range
2+
3+
import com.baeldung.inputstream.readUpToNullChar
4+
import kotlinx.io.core.use
5+
import org.junit.Test
6+
import java.io.BufferedReader
7+
import java.io.File
8+
import kotlin.test.assertEquals
9+
10+
class InputStreamToStringTest {
11+
private val fileName = "src/test/resources/inputstream2string.txt"
12+
private val fileFullContent = "Computer programming can be a hassle\r\n" +
13+
"It's like trying to take a defended castle"
14+
private val fileContentUpToNullChar = "Computer programming can be a hassle\r\n" +
15+
"It"
16+
17+
@Test
18+
fun whenReadFileWithBufferedReader_thenFullFileContentIsReadAsString() {
19+
val file = File(fileName)
20+
val inputStream = file.inputStream()
21+
val content = inputStream.bufferedReader().use(BufferedReader::readText)
22+
assertEquals(fileFullContent, content)
23+
}
24+
25+
@Test
26+
fun whenReadFileUpToNullChar_thenPartBeforeNullCharIsReadAsString() {
27+
val file = File(fileName)
28+
val inputStream = file.inputStream()
29+
val content = inputStream.use { it.readUpToNullChar('\'') }
30+
assertEquals(fileContentUpToNullChar, content)
31+
}
32+
33+
@Test
34+
fun whenReadFileWithoutContainingNullChar_thenFullFileContentIsReadAsString() {
35+
val file = File(fileName)
36+
val inputStream = file.inputStream()
37+
val content = inputStream.use { it.readUpToNullChar('-') }
38+
assertEquals(fileFullContent, content)
39+
}
40+
41+
42+
}
43+
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Computer programming can be a hassle
2+
It's like trying to take a defended castle

0 commit comments

Comments
 (0)