如何将字节读入字节数组?在java中,我将字节数组初始化为byte[] b = new byte[100],然后将其传递给相应的方法.然而在Kotlin中,我无法用缓冲区应该有多少字节来初始化ByteArray.

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

推荐答案

最简单的方法是使用

File("aaa").readBytes()

那个人会把整个文件读到ByteArray.但是您应该小心地知道堆中有足够的RAM来执行此操作

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

Kotlin相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

T和T有什么区别:任何>

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

如何在Docker中使用Selenium和chromedriver?

使用 kotlin 流删除 map 中具有某些相似性的值

Kotlin 启动与启动(Dispatchers.Default)

如何通过 compose 处理剪切区域?

嵌套数组 indexOf()

基类中的 ViewModelProviders.get(...)

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

Mockito 的 argThat 在 Kotlin 中返回 null

空对象引用上的 TransitionSet ArrayList.size()

在Kotlin中使用@Service时引发异常

用于代码生成的ANTLR工具版本4.7.1与当前运行时版本4.5.3不匹配

如何将 CameraView 与 Jetpack Compose 一起使用?

如何计算Kotlin中的百分比

如何根据ArrayList的对象属性值从中获取最小/最大值?

访问Kotlin中的属性委托

从 Kotlin 访问 Integer.class