Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin reading from file into byte array

Tags:

android

kotlin

How do I read bytes into a Byte Array? In java I used to initialize byte array as byte[] b = new byte[100] and then pass that to the corresponding method. However in Kotlin, I am unable to initialize ByteArray with how many bytes the buffer should have.

In other words, how do I use this function?: https://developer.android.com/reference/kotlin/java/io/RandomAccessFile#read(kotlin.ByteArray)

like image 354
arun Avatar asked Mar 29 '19 11:03

arun


People also ask

How to convert file into byte array in Kotlin?

Example 1: Convert File to byte[] In the above program, we store the path to the file in the variable path . Then, inside the try block, we read all the bytes from the given pth using readAllBytes() method. Then, we use Arrays ' toString() method to print the byte array.

How do I read the contents of a Kotlin file?

1) Select "Project" from the top of the vertical toolbar to open the project "tool window" 2) From the drop-down menu at the top of the "tool window", select "Android" 3) Right-click on "App" and select "New" then -> "Folder" (the one with the green Android icon beside it) then -> "Assets Folder" 4) Right-click on the ...

What is FileOutputStream in Kotlin?

FileOutputStream(name: String!) Creates a file output stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.


1 Answers

The easiest way is to use

File("aaa").readBytes()

That one will read the whole file into the ByteArray. But you should carefully know you have enough RAM in the heap to do so

The ByteArray can be created via ByteArray(100) call, where 100 is the size of it

For the RandomAccessFile, it is probably better to use at the readFully function, which reads exactly the requested amount of bytes.

The classic approach is possible to read a file by chunks, e.g.

    val buff = ByteArray(1230)
    File("aaa").inputStream().buffered().use { input ->
      while(true) {
        val sz = input.read(buff)
        if (sz <= 0) break

        ///at that point we have a sz bytes in the buff to process
        consumeArray(buff, 0, sz)
      }
    }
like image 52
Eugene Petrenko Avatar answered Sep 18 '22 11:09

Eugene Petrenko