How do I archive multiple files into a .zip file using scala?

后端 未结 6 1177
孤独总比滥情好
孤独总比滥情好 2020-12-14 19:41

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 filename

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 19:56

    The Travis answer is correct but I have tweaked a little to get a faster version of his code:

    val Buffer = 2 * 1024
    
    def zip(out: String, files: Iterable[String], retainPathInfo: Boolean = true) = {
      var data = new Array[Byte](Buffer)
      val zip = new ZipOutputStream(new FileOutputStream(out))
      files.foreach { name =>
        if (!retainPathInfo)
          zip.putNextEntry(new ZipEntry(name.splitAt(name.lastIndexOf(File.separatorChar) + 1)._2))
        else
          zip.putNextEntry(new ZipEntry(name))
        val in = new BufferedInputStream(new FileInputStream(name), Buffer)
        var b = in.read(data, 0, Buffer)
        while (b != -1) {
          zip.write(data, 0, b)
          b = in.read(data, 0, Buffer)
        }
        in.close()
        zip.closeEntry()
      }
      zip.close()
    }
    

提交回复
热议问题