0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

やりたいこと

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

  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)
    }
  }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?