Tra*_*own 21
目前没有任何方法可以从标准的Scala库中执行此类操作,但它非常易于使用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()
}
Run Code Online (Sandbox Code Playgroud)
我在这里专注于简单而不是效率(没有错误检查,一次读取和写入一个字节并不理想),但它可以工作,并且可以很容易地进行改进.
我最近也不得不使用zip文件,并发现这个非常好的实用程序:https://github.com/zeroturnaround/zt-zip
这是压缩目录中所有文件的示例:
import org.zeroturnaround.zip.ZipUtil
ZipUtil.pack(new File("/tmp/demo"), new File("/tmp/demo.zip"))
Run Code Online (Sandbox Code Playgroud)
很方便.
如果您喜欢功能性,这是更多的 Scala 风格:
def compress(zipFilepath: String, files: List[File]) {
def readByte(bufferedReader: BufferedReader): Stream[Int] = {
bufferedReader.read() #:: readByte(bufferedReader)
}
val zip = new ZipOutputStream(new FileOutputStream(zipFilepath))
try {
for (file <- files) {
//add zip entry to output stream
zip.putNextEntry(new ZipEntry(file.getName))
val in = Source.fromFile(file.getCanonicalPath).bufferedReader()
try {
readByte(in).takeWhile(_ > -1).toList.foreach(zip.write(_))
}
finally {
in.close()
}
zip.closeEntry()
}
}
finally {
zip.close()
}
}
Run Code Online (Sandbox Code Playgroud)
并且不要忘记进口:
import java.io.{BufferedReader, FileOutputStream, File}
import java.util.zip.{ZipEntry, ZipOutputStream}
import io.Source
Run Code Online (Sandbox Code Playgroud)