decodingWith

JVM
1.8
@ExperimentalEncodingApi fun InputStream.decodingWith(
    base64: Base64
): InputStream

(source)

Returns an input stream that decodes symbols from this input stream using the specified base64 encoding. Please refer to Base64 documentation for more details on the encoding itself.

Reading from the returned input stream leads to reading some symbols from the underlying input stream. The symbols are decoded using the specified base64 encoding and the resulting bytes are returned. Symbols are decoded in 4-symbol blocks.

The requirement, prohibition, or optionality of padding in the input symbols is determined by the PaddingOption set for the base64 instance. The padding character '=' is interpreted as the end of the symbol stream. Subsequent symbols are not read even if the end of the underlying input stream is not reached.

The returned input stream should be closed in a timely manner. We suggest you try the use function, which closes the resource after a given block of code is executed. The close operation discards leftover bytes. Closing the returned input stream will close the underlying input stream.

import java.io.*
import kotlin.io.encoding.*

fun main(args: Array<String>) {
//sampleStart
ByteArrayInputStream("SGVsbG8gV29ybGQh".toByteArray()).decodingWith(Base64.Default).use {
    println(it.readBytes().decodeToString()) // Hello World!
}

ByteArrayInputStream("UGFkOg==... and everything else".toByteArray()).use { input ->
    input.decodingWith(Base64.Default).also {
        // Reads only Base64-encoded part, including padding
        println(it.readBytes().decodeToString()) // Pad:
    }
    // The original stream will only contain remaining bytes
    println(input.readBytes().decodeToString()) // ... and everything else
}
//sampleEnd
}

See Also

Base64