Search code examples
javakotlinsocketsionull-character

Reading up to null character in Kotlin character by character from socket response


So say I have a stream being returned from a socket connection. The stream is being returned terminated with '\0' but in kotlin I can't seem to get this to work the same way. The code below is in Java and I am probably just over looking something simple.

public final String readUpToNull(InputStream inputStream) throws IOException {
    StringBuilder builder = new StringBuilder();
    char ch;
    while ((ch = (char) inputStream.read()) != '\0') {
        builder.append(ch);
    }
    return builder.toString();
}

If anyone knows how to do this while communicating with a socket with the streams in Kotlin. The other post that is on here is covering reading the full string of text. The socket is returning a longer string delimited by the '\0'. So the issue is I need to be able to load up the first string then the second string.

Example

Server : hello\0 xml stuff all right here\0
Client: read hello
Client: read xml stuff all right here

Example code from kotlinlang.org shows this as a solution using the Java to Kotlin converter. Note that this code does not compile because of the assignment in the while statement.

@Throws(IOException::class)
fun readUpToNull(inputStream:InputStream):String {
    val builder = StringBuilder()
    val ch:Char
    while ((ch = inputStream.read() as Char) != '\u0000')
    {
      builder.append(ch)
    }
    return builder.toString()
}

Here is what I have so far but the this implementation is just hanging up the processes and is locking the unit test for the API call.

fun readUpToNull(stream: InputStream): String {
    val reader = BufferedReader(InputStreamReader(stream))
    val builder = StringBuilder()
    while (true) {
        val characters = reader.readText().toCharArray()
        characters.takeWhile { it != '\u0000' }.forEach { builder.append(it) }
        break
    }
    return builder.toString()
}

Solution

  • Here's a more-or-less direct translation of your Java code to Kotlin:

    fun readUpToNull(inputStream: InputStream): String {
        return buildString {
            while (true) {
                val ch = inputStream.read().toChar()
                if (ch == '\u0000') break
                append(ch)
            }
        }
    }