我正在尝试在Kotlin中创建一个zip文件。这是代码:
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()}
Run Code Online (Sandbox Code Playgroud)
zip文件已创建,但其中的文件已损坏!
如果您使用Kotlin的IOStreams.copyTo()扩展程序,它将为您完成复制工作,最终为我工作。
因此,替换为:
origin.buffered(1024).reader().forEachLine {
out.write(data)
}
Run Code Online (Sandbox Code Playgroud)
有了这个:
origin.copyTo(out, 1024)
Run Code Online (Sandbox Code Playgroud)
我也遇到了ZipEntry一个很大的斜线问题,但这可能只是因为我在Windows上。
注意:我并不需要最终closeEntry()使它起作用,但是建议这样做。
我做了一个混合:
fun main(args: Array<String>) {
val files: Array<String> = arrayOf("/home/matte/theres_no_place.png", "/home/matte/vladstudio_the_moon_and_the_ocean_1920x1440_signed.jpg")
ZipOutputStream(BufferedOutputStream(FileOutputStream("/home/matte/Desktop/test.zip"))).use { out ->
for (file in files) {
FileInputStream(file).use { fi ->
BufferedInputStream(fi).use { origin ->
val entry = ZipEntry(file.substring(file.lastIndexOf("/")))
out.putNextEntry(entry)
origin.copyTo(out, 1024)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它完美地工作!非常感谢双方!
小智 2
我不确定您是否想手动执行此操作,但我发现这个库可以完美运行:
https://github.com/zeroturnaround/zt-zip
该库是 Java Zip Utils 库的一个很好的包装,其中包括使用单个函数压缩/解压缩文件和目录的方法。
要压缩单个文件,您只需要使用以下packEntry方法:
ZipUtil.packEntry(File("/tmp/demo.txt"), File("/tmp/demo.zip"))
Run Code Online (Sandbox Code Playgroud)
对于压缩目录及其子目录的情况,您可以使用以下pack方法:
val dirToCompress = Paths.get("/path/to/my/dir").toFile()
val targetOutput = Paths.get("/output/path/dir.zip").toFile()
ZipUtil.pack(dirToCompress, targetOutput)
Run Code Online (Sandbox Code Playgroud)
zip 文件应该已在指定的目标输出中创建。
您可以在库的文档中找到更多详细信息和示例。
希望这有帮助 =)
| 归档时间: |
|
| 查看次数: |
4588 次 |
| 最近记录: |