, 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!
Emmanuel Oga
10/01/2020, 7:41 AM
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
Vampire
10/01/2020, 7:51 AM
As you have a
ByteArrayOutputStream
, you can also simply use a
ByteArrayInputStream
. The data is fully in RAM already anyway.
e
Emmanuel Oga
10/01/2020, 8:03 AM
isn't that going to make a copy of the data? (duplicate)
Emmanuel Oga
10/01/2020, 8:05 AM
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
Vampire
10/01/2020, 8:12 AM
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.