[英]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.我正在尝试使用此 Java 代码,但在 Android Studio 中将其转换为 Kotlin,但我在 Kotlin 中找不到setSize(..)
和.length
在 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();
}
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
.阵列中科特林具有size
字段,而不是Java数组length
和size
字段是Int
在科特林,但ZipEntry.setSize(long size)
只接受long
。 So you can do something like this:所以你可以做这样的事情:
entry.setSize(input.size.toLong())
Or in more Kotlin idiomatic way:或者以更符合 Kotlin 习惯的方式:
entry.size = input.size.toLong()
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:你在 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()
}
when you write a byteArray in kotlin like this :当您像这样在 kotlin 中编写 byteArray 时:
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[]
.当面向 JVM 时,此类的实例表示为byte[]
。 @constructor Creates a new array of the specified [size], with all elements initialized to zero. @constructor 创建一个指定 [size] 的新数组,所有元素都初始化为零。
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.但是size
类型是int
并且entry.size
需要一个long
值,只需将.toLong()
添加到size
解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.