添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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

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

Thanks!