[Solved] Close stream InputStream.readBytes()

Hi!

I noticed that the extension readBytes from InputStream is not closing the ByteArrayOutputStream. Why not?

 Reads this stream completely into a byte array.
 
 Note: It is the caller's responsibility to close this stream.
 
@SinceKotlin( **"1.3"** )
public fun InputStream.readBytes(): ByteArray {
  val buffer = ByteArrayOutputStream(maxOf ( *DEFAULT_BUFFER_SIZE , this.available()))
  copyTo(buffer)
  return buffer.toByteArray()
}

And internally copyTo says that is caller’s responsible to close both streams.

/*Copies this stream to the given output stream, returning the number of bytes copied  *  * **Note** It is the caller's responsibility to close both of these resources.  */
public fun InputStream.copyTo(out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE): Long {
      ... code ...
}

But readBytes doesn’t close outputstream so… it’s a memory leak? What am i missing? For me readBytes extension should be:

fun InputStream.readBytes(): ByteArray {
ByteArrayOutputStream(maxOf(DEFAULT_BUFFER_SIZE, this.available())).use {
    copyTo(it)
    return it.toByteArray()
 }
}

Thanks a lot

1 Like

Besides the allocated memory, ByteArrayOutputStream has nothing to clean up. Its close operation is a no-op. The garbage collector will take care of the memory as there is no reference to it anymore after readBytes() finishes.

2 Likes

Then closing a ByteArrayOutputStream does nothing. Understood now… sorry for my newbie question.

Thanks!

Actually, it does close it. use closes the receiver upon upon exit.