basically to get a bytearray from an input stream
# announcements
z
basically to get a bytearray from an input stream
z
that's what I'm using (I'm about to test it). But it's kind of ugly because I can't just say
getInputStream().asBytes()
but I need to have the stream in a variable
r
I'm not sure I follow you. Mind posting a snippet of what you find inconvenient?
z
Copy code
val inputStream = getFileInputStream()
inputStream.readBytes(inputStream.available())
r
Oh, I see, you are talking about the case when you have all the needed info in stream. You can simply write the following extension function for your case and use it elsewhere:
Copy code
fun InputStream.readAvailableBytes(): ByteArray = this.readBytes(this.available())
z
Yeah I think I will, thanks!
r
Taking a look into the source code, you can just use
readBytes(0)
due to this:
val buffer = ByteArrayOutputStream(Math.max(estimatedSize, this.available()))
https://github.com/JetBrains/kotlin/blob/1.2.0/libraries/stdlib/src/kotlin/io/IOStreams.kt#L115
z
I can just avoid passing a size. It seems to work, not sure why 😄
I mean I know they use a default value but higher that what I actually need in this case.
r
It's probably useful for buffered input streams which provide data in portions --
available()
can be small, but more data will appear as soon as you start pulling. So it's reasonable to have some minimal buffer size. In your case it sounds more logical to pass 0.
z
Yeah makes sense