如何使用 Scala 将多个文件归档到 .zip 文件中? [英] How do I archive multiple files into a .zip file using scala?
本文介绍了如何使用 Scala 将多个文件归档到 .zip 文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以发布一个简单的代码片段吗?
Could anyone post a simple snippet that does this?
文件是文本文件,因此压缩比归档文件更好.
Files are text files, so compression would be nice rather than just archive the files.
我将文件名存储在可迭代对象中.
I have the filenames stored in an iterable.
推荐答案
目前没有任何方法可以从标准 Scala 库中执行此类操作,但是使用起来非常简单 java.util.zip
::>
There's not currently any way to do this kind of thing from the standard Scala library, but it's pretty easy to use java.util.zip
:
def zip(out: String, files: Iterable[String]) = {
import java.io.{ BufferedInputStream, FileInputStream, FileOutputStream }
import java.util.zip.{ ZipEntry, ZipOutputStream }
val zip = new ZipOutputStream(new FileOutputStream(out))
files.foreach { name =>
zip.putNextEntry(new ZipEntry(name))
val in = new BufferedInputStream(new FileInputStream(name))
var b = in.read()
while (b > -1) {
zip.write(b)
b = in.read()
}
in.close()
zip.closeEntry()
}
zip.close()
}
我在这里关注的是简单性而不是效率(没有错误检查并且一次读写一个字节并不理想),但它确实有效,并且可以很容易地改进.
I'm focusing on simplicity instead of efficiency here (no error checking and reading and writing one byte at a time isn't ideal), but it works, and can very easily be improved.
这篇关于如何使用 Scala 将多个文件归档到 .zip 文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文