Folder compression with Scala. Using java.util.zip.ZipOutputStream.

Thing you want to do

As the title says. For memos.

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

Recommended Posts

Folder compression with Scala. Using java.util.zip.ZipOutputStream.
Using Pair with OpenJDK
Try using GloVe with Deeplearning4j
Try using view_component with rails
Japaneseize using i18n with Rails
Using Mapper with Java (Spring)
[Introduction] Build MVC with Scala
Using PlantUml with Honkit [Docker]