Hi. I have some code that writes to an `OutputStre...
# announcements
e
Hi. I have some code that writes to an
OutputStream
, and some code that needs that data but wants to read from an
InputStream
. I came up with this but I was wondering if maybe thre's a more straightforward solution:
Copy code
/**
 * Pipe output to an input stream. Uses a thread to write from output to input.
 * See: <https://stackoverflow.com/questions/5778658/how-to-convert-outputstream-to-inputstream>
 */
fun ByteArrayOutputStream.asInputStream(): InputStream = PipedInputStream().also { istream ->
    PipedOutputStream(istream).let { ostream ->
        Thread { ostream.use { writeTo(ostream) } }.start()
    }
}
Thanks!
Piped streams seem fine but Kotlin sometimes have pre defined extension functions for helpers and what not, I wonder if there's something to perform this kind of conversion already
v
As you have a
ByteArrayOutputStream
, you can also simply use a
ByteArrayInputStream
. The data is fully in RAM already anyway.
e
isn't that going to make a copy of the data? (duplicate)
if I get it right yes, that would create an additional copy
ByteArrayInputStream(prevOutput.toByteArray())
(doens't seem to be a way to do it without the copy or the pipe)
v
Well, it will make a new copy of the array, yes. Without copy you will probably have to use piped streams and threads, yes. But consider whether the data is small enough to still do the copy. Thread sheduling is not one of the cheapest things. So needing a bit more ram might rectify not using threads.
e
gotcha