Android 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(); 

我将代码更改为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会自动刷新它。