Alejandra Sandoval
Alejandra Sandoval

Reputation: 1

Zip byte[] in Kotlin. Java code to Kotlin

I'm trying to use this Java code but converting it to Kotlin in Android Studio, but I don't find a equivalent in kotlin for setSize(..) and .length in Kotlin. Could anyone help me?

public static byte[] zipBytes(String filename, byte[] input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(filename);
    entry.setSize(input.length);
    zos.putNextEntry(entry);
    zos.write(input);
    zos.closeEntry();
    zos.close();
    return baos.toByteArray();
}

Upvotes: 0

Views: 1376

Answers (3)

Mojtaba Haddadi
Mojtaba Haddadi

Reputation: 1376

when you write a byteArray in kotlin like this :

 val byteArray = ByteArray(1024)
 var length = byteArray.size

documentation says

An array of bytes. When targeting the JVM, instances of this class are represented as byte[]. @constructor Creates a new array of the specified [size], with all elements initialized to zero.

to prove it, checking the byte code created is this:

 byte[] byteArray = new byte[1024];
 int test = byteArray.length;

therefor in your case a can code like this.

entry.size = byteArray.size

but type of size is int and entry.size needs a long value, just add .toLong() to size for fixing this issue.

Upvotes: 1

V.March
V.March

Reputation: 1840

Try to use this code:

Import:

import java.io.IOException
import java.text.DecimalFormat
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

And you code in kotlin:

@Throws(IOException::class)
fun zipBytes(filename: String?, input: ByteArray): ByteArray? {
    val baos = ByteArrayOutputStream()
    val zos = ZipOutputStream(baos)
    val entry = ZipEntry(filename)
    entry.size = input.size.toLong()
    zos.putNextEntry(entry)
    zos.write(input)
    zos.closeEntry()
    zos.close()
    return baos.toByteArray()
}

Upvotes: 0

Igor Khvostenkov
Igor Khvostenkov

Reputation: 744

Array in Kotlin has size field instead of Java array length and size field is Int in Kotlin, but ZipEntry.setSize(long size) accepts only long. So you can do something like this:

entry.setSize(input.size.toLong())

Or in more Kotlin idiomatic way:

entry.size = input.size.toLong()

Upvotes: 1

Related Questions