Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
kotlin reading from file into byte array

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)

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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)
      }
    }
over 4 years ago · Santiago Trujillo Relatório

0

I found this worked nicely:

fun File.chunkedSequence(chunk: Int): Sequence<ByteArray> {
    val input = this.inputStream().buffered()
    val buffer = ByteArray(chunk)
    return generateSequence {
        val red = input.read(buffer)
        if (red >= 0) buffer.copyOf(red)
        else {
            input.close()
            null
        }
    }
}

Use it like this.

    file.chunkedSequence(CHUNK_SIZE).forEach {
        // Do something with `it`
    }

Not an exact match to your question but this is the question that came up when I was looking to chunk a file into a sequence of byte arrays.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda