https://kotlinlang.org logo
Title
z

ziggy42

01/16/2018, 2:25 PM
basically to get a bytearray from an input stream
z

ziggy42

01/16/2018, 3:10 PM
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

r4zzz4k

01/16/2018, 3:14 PM
I'm not sure I follow you. Mind posting a snippet of what you find inconvenient?
z

ziggy42

01/16/2018, 4:28 PM
val inputStream = getFileInputStream()
inputStream.readBytes(inputStream.available())
r

r4zzz4k

01/16/2018, 4:35 PM
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:
fun InputStream.readAvailableBytes(): ByteArray = this.readBytes(this.available())
z

ziggy42

01/16/2018, 4:36 PM
Yeah I think I will, thanks!
r

r4zzz4k

01/16/2018, 4:38 PM
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

ziggy42

01/16/2018, 4:41 PM
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

r4zzz4k

01/16/2018, 4:45 PM
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

ziggy42

01/16/2018, 5:07 PM
Yeah makes sense