Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Scalaでフォルダ圧縮。java.util.zip.ZipOutputStreamを使って。

More than 1 year has passed since last update.

やりたいこと

タイトル通りです。メモ用。

  import java.io._
  import java.nio.charset.Charset
  import java.util.zip.{ZipEntry, ZipOutputStream}

  def main(args: Array[String]): Unit = {
    zipFolder("file\\folder", "file\\folder.zip", "Shift_JIS")
  }

  def zipFolder(targetDir: String, outputZip: String, mojiCode: String): Unit = {
    val baseFile = new File(targetDir)
    val zos = new ZipOutputStream(new FileOutputStream(new File(outputZip)), Charset.forName(mojiCode))
    val fileList: Seq[File] = baseFile.listFiles()
    zipFileList(zos, fileList, baseFile)
    zos.closeEntry()
    zos.close()
  }

  private def zipFileList(zos: ZipOutputStream, fileList: Seq[File], baseFile: File): Unit = {
    for (file <- fileList) {
      if (file.isDirectory) {
        zipFileList(zos, file.listFiles(), baseFile)
      } else {
        entryZos(file, zos, baseFile)
      }
    }
  }

  private def entryZos(targetFile: File, zos: ZipOutputStream, baseFile: File): Unit = {
    val entry = new ZipEntry(targetFile.getAbsolutePath.replace(baseFile.getParentFile.getAbsolutePath, "").drop(1))
    zos.putNextEntry(entry)
    val in = new BufferedInputStream(new FileInputStream(targetFile))
    writeZos(zos, in, targetFile)
    in.close()
  }

  private def writeZos(zos: ZipOutputStream, in: BufferedInputStream, targetFile: File) : Unit = {
    val readBytes = in.read()
    if (readBytes != -1) {
      zos.write(readBytes)
      writeZos(zos, in, targetFile)
    }
  }
is3
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away