About write a UByteArray to the file

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

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.

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.

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

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

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}}

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.

OK, I understand now! Thanks a lot!

The underlying ByteArray can be obtained with asByteArray extension function:

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

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>

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

Thanks again. It should be asByteArray then.

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.

1 Like