I'm trying to create a zip file in Kotlin. this is the code:

fun main(args: Array<String>) {
var files: Array<String> = arrayOf("/home/matte/theres_no_place.png", "/home/matte/vladstudio_the_moon_and_the_ocean_1920x1440_signed.jpg")
var out = ZipOutputStream(BufferedOutputStream(FileOutputStream("/home/matte/Desktop/test.zip")))
var data = ByteArray(1024)
for (file in files) {
    var fi = FileInputStream(file)
    var origin = BufferedInputStream(fi)
    var entry = ZipEntry(file.substring(file.lastIndexOf("/")))
    out.putNextEntry(entry)
    origin.buffered(1024).reader().forEachLine {
        out.write(data)
    }
    origin.close()
}
out.close()}

zip文件已创建,但其中的文件已损坏!

推荐答案

如果你使用Kotlin的IOStreams.copyTo()扩展,它将为你完成复制工作,而这最终对我有效.

So replace this:

origin.buffered(1024).reader().forEachLine {
    out.write(data)
}

With this:

origin.copyTo(out, 1024)

I also had issues with the ZipEntry having a leading slash, but that could just be because I'm on Windows.

Note: I didn't end up needing to call closeEntry() to get this to work but it is recommended.

Kotlin相关问答推荐

在Kotlin中可以连接两个范围吗?

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

带有Spring Boot和Kotline的可嵌入实体

Android Jetpack编写androidx.compose.oundation.lazy.grid.Items

如何让 LocalDateTime.parse 拒绝 24:00 时间

如何在 kotlin 中的数据类中为变量提供多种类型

Kotlin 接口类型参数

Kotlin 中的 maxOf() 和 max() 方法有什么区别?

在kotlin中匹配多个变量

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

Koin Android:org.koin.error.NoBeanDefFoundException

Kotlin 方法重载

Firebase 权限被拒绝

更新到版本4.10.1/4.10.2后 Gradle 同步失败

未找到导入 kotlinx.coroutines.flow.*

如何暂停kotlin coroutine直到收到通知

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

Kotlin 与 C# 中的标志枚举变量具有相似效果的方式是什么

Android Studio - java.io.IOException:无法生成 v1 签名

如何修复未解析的参考生命周期范围?