About write a UByteArray to the file


#1

Is there any way to write a UbyteArray to the file directly?


#2

What do you mean by directly? You can convert them to regular bytes on flight and use standard channels for writing. You can also add an extension to the channel or ByteBuffer for that.


#3

Thanks for your replay. I mean that such as a 100,000 size UByteArray which stores some data via calculation. In that case, if I want to write it to the file, is there the only way that you mentioned I can do? May be it takes a little time to convert.


#4

It takes zero time to convert since UByte are inline class, no real conversion is made, just compile-time change of name.


#5

May you offer me a sample for conversion that you said? I tried, but can not find a right way. Thanks a lot !


#6

Sadly, UByteArray does not expose underlying ByteArray. If you are using io streams to write to file, you can do:

val stream = <create file output stream here>
uByteArray.forEach{ stream.write(it.toByte}}
stream.flush()

Be sure to use buffered stream, otherwise performance will be terrible.
When reading you can use Byte::toUByte to convert it back.

By the way, i think that UByteArray needs method to expose underlying ByteArray for such operations.


#7

OK, I understand now! Thanks a lot!


#8

The underlying ByteArray can be obtained with asByteArray extension function:

fun main() {
    val uarray = ubyteArrayOf(255u, 0u)
    val array = uarray.asByteArray()
    println(array.contentToString())
}

#9

Thank you very much. I was looking into source and did not think it could reside in different file.

It means that serializing UByteArray is even more simple.

val channel= <create file channel>
channel.write(ByteBuffer.wrap(uByteArray.toByteArray()))

#10

Note that toByteArray copies the content, whereas asByteArray provides the view to the same content as an array of signed bytes.


#11

Thanks again. It should be asByteArray then.


#12

I think it’s worth to mention again that this is true for all functions in kotlin (std-lib). toSomething creates a copy while asSomething returns a wrapper or the underlying implementation.