如何使用scala将多个文件存档到.zip文件中?

Pic*_*ico 15 scala zipfile

任何人都可以发布一个简单的代码片段吗?

文件是文本文件,因此压缩会很好,而不仅仅是归档文件.

我将文件名存储在iterable中.

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)

我在这里专注于简单而不是效率(没有错误检查,一次读取和写入一个字节并不理想),但它可以工作,并且可以很容易地进行改进.


Gab*_*lla 8

我最近也不得不使用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)

很方便.


Geo*_*los 5

如果您喜欢功能性,这是更多的 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)