在Kotlin中创建文件ZIP [英] Create file ZIP in Kotlin

查看:371
本文介绍了在Kotlin中创建文件ZIP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Kotlin中创建一个zip文件. 这是代码:

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文件,但其中的文件已损坏!

the zip file is created, but the files inside are corrupt!

推荐答案

如果您使用Kotlin的IOStreams.copyTo()扩展名,它将为您完成复制工作,最终为我工作.

If you use Kotlin's IOStreams.copyTo() extension, it will do the copying work for you, and that ended up working for me.

所以替换掉它:

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

与此:

origin.copyTo(out, 1024)

我也遇到了ZipEntry斜杠开头的问题,但这可能只是因为我在Windows上.

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

注意:我最终并不需要致电closeEntry()来使它正常工作,但建议这样做.

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

这篇关于在Kotlin中创建文件ZIP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆