在 Kotlin 中创建一个 ZIP 文件 [英] Create a ZIP file in Kotlin
本文介绍了在 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屋!
查看全文