Android Kotlin打开资产文件

kib*_*bar 0 android inputstream kotlin

我想打开资产文件.在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();
Run Code Online (Sandbox Code Playgroud)

我将代码更改为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()
        }
    }
Run Code Online (Sandbox Code Playgroud)

Bla*_*der 6

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

这是Kotlin的写作方式:

FileOutputStream(LOCATION).use { out ->
    context.assets.open(Database.ASSET).use {
        it.copyTo(out)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

注意2:关闭OutputStream会自动刷新它.