Android Kotlin 打开资产文件

Android Kotlin open asset file

我想打开资产文件。在 java 代码工作之前,但是当我将代码更改为 kotlin 时,它不起作用。

Java 对其工作进行编码

        InputStream  streamIN = new BufferedInputStream(context.getAssets().open(Database.ASSET));
        OutputStream streamOU = new BufferedOutputStream(new FileOutputStream(LOCATION));
        byte[] buffer = new byte[1024];
        int length;
        while ((length = streamIN.read(buffer)) > 0) {
            streamOU.write(buffer, 0, length);
        }

        streamIN.close();
        streamOU.flush();
        streamOU.close();

我将代码更改为 Kotlin,但它不起作用

    var length: Int
    val buffer = ByteArray(1024)
    BufferedOutputStream(FileOutputStream(LOCATION)).use {
        out ->
        {
            BufferedInputStream(context.assets.open(Database.ASSET)).use {
                length = it.read(buffer)
                if (length > 0) out.write(buffer, 0, length)
            }

            out.flush()
        }
    }

您的 Kotlin 代码中没有循环,因此您只读写前 1024 个字节。

这是 Kotlin 的写法:

FileOutputStream(LOCATION).use { out ->
    context.assets.open(Database.ASSET).use {
        it.copyTo(out)
    }
}

注意 1:您不需要缓冲 InputStream 或 OutputStream,因为复制操作本身已经使用字节缓冲区。

注2:关闭OutputStream会自动刷新。