if I have to write a `ByteBuffer` to file, what's ...
# getting-started
e
if I have to write a
ByteBuffer
to file, what's the best way? Using
InputStream
like here: https://stackoverflow.com/questions/35528409/write-a-large-inputstream-to-file-in-kotlin?
d
Embrace `java.nio`:
Copy code
fun Path.channel(vararg options: OpenOption): FileChannel = FileChannel.open(this, *options)

fun main(args: Array<String>) {
    val buf: ByteBuffer = TODO()
    val file = Paths.get("output")

    file.channel(StandardOpenOption.CREATE, StandardOpenOption.WRITE).use { channel ->
        while (buf.hasRemaining()) channel.write(buf)
    }
}
e
why
while (buf.hasRemaining())
and not simply
channel.write(buf)
?
can it simply write an arbitrarly amount of bytes? Why?
I'll never get these methods..
d
Yes,
channel.write
may write only a portion of the buffer as per the Javadocs.
If you feed it a large buffer, it will only write as much as it can efficiently write in one go.
e
what does it mean?
for which reason would it efficientely write only a portion?
d
Channel
is a very generic interface. It might be a channel bound to a network socket, which only has a limited buffer. You can't just send out 500MB immediately, you have to wait for the network speed. So as long as the network buffer is full, it cannot write.
e
ah, that makes sense, thanks
hi, just a quick question, this is valid also for reading I guess
Copy code
val buffer = FileChannel.open(path, StandardOpenOption.READ).use { channel ->
            bufferBig(channel.size().i).also {
                while (channel.read(it) > 0) Unit
            }
        }
read()
returns the number of bytes read
d
Yes, but why
also
here?