Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Kotlin open asset file

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()
        }
    }
like image 885
kibar Avatar asked Jan 04 '23 17:01

kibar


1 Answers

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.

like image 52
BladeCoder Avatar answered Jan 06 '23 08:01

BladeCoder