I want to open asset file. Before the java code is worked but When I was change code to kotlin it doesn't work.
Java code its work
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();
I change code to Kotlin but It doesn't work
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()
}
}
There is no loop in your Kotlin code, so you are only reading and writing the first 1024 bytes.
Here's the Kotlin way of writing it:
FileOutputStream(LOCATION).use { out ->
context.assets.open(Database.ASSET).use {
it.copyTo(out)
}
}
Note 1: you don't need to buffer the InputStream or the OutputStream since the copy operation itself already uses a byte buffer.
Note 2: closing the OutputStream will flush it automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With