Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 306 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
kotlin reading from file into byte array

#1
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?:

[To see links please register here]

Reply

#2
The easiest way is to use
```kotlin
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.
```kotlin
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)
}
}
```
Reply

#3
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.
Reply

#4

File.readBytes() //limited 2GB

Don't forget it has an internal limitation of 2 GB byte array size. So to read all bytes we should use stream like:

FileInputStream(File(uri)).use {
val allBytes = it.readBytes()
}

Also you can use readAllBytes for Android API >= 26:

Files.readAllBytes(Paths.get(filePath))
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through