readTo

fun Source.readTo(sink: ByteArray, startIndex: Int = 0, endIndex: Int = sink.size)(source)

Removes exactly endIndex - startIndex bytes from this source and copies them into sink subrange starting at startIndex and ending at endIndex.

Parameters

sink

the array to write data to

startIndex

the startIndex (inclusive) of the sink subrange to read data into, 0 by default.

endIndex

the endIndex (exclusive) of the sink subrange to read data into, sink.size by default.

Throws

when the requested number of bytes cannot be read.

when the source is closed.

when startIndex or endIndex is out of range of sink array indices.

when startIndex > endIndex.

when some I/O error occurs.

Samples

import kotlinx.io.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   val buffer = Buffer()
buffer.write(byteArrayOf(1, 2, 3, 4, 5, 6, 7))

val out = ByteArray(10)
buffer.readTo(out, startIndex = 1, endIndex = 4)
assertContentEquals(byteArrayOf(0, 1, 2, 3, 0, 0, 0, 0, 0, 0), out)
assertContentEquals(byteArrayOf(4, 5, 6, 7), buffer.readByteArray()) 
   //sampleEnd
}
fun Buffer.readTo(out: OutputStream, byteCount: Long = size)(source)

Consumes byteCount bytes from this buffer and writes it to out.

Parameters

out

the OutputStream to write to.

byteCount

the number of bytes to be written, Buffer.size by default.

Throws

when byteCount is negative or exceeds the buffer size.

Samples

import kotlinx.io.*
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.test.*

fun main() { 
   //sampleStart 
   val buffer = Buffer()
buffer.writeString("hello")

val outputStream = ByteArrayOutputStream()
buffer.readTo(outputStream)

assertTrue(buffer.exhausted())

val inputStream = ByteArrayInputStream(outputStream.toByteArray())
buffer.transferFrom(inputStream)

assertEquals("hello", buffer.readString()) 
   //sampleEnd
}