Skip to content

Instantly share code, notes, and snippets.

@gekomad
Last active January 25, 2019 11:08
Show Gist options
  • Save gekomad/209df0d6a532bb87d4a087dcc4ddf948 to your computer and use it in GitHub Desktop.
Save gekomad/209df0d6a532bb87d4a087dcc4ddf948 to your computer and use it in GitHub Desktop.
Scala Zip with cats IO
package trackit.helper
import java.io.{File, FileInputStream, FileOutputStream}
import cats.effect.IO
import cats.effect.Resource.fromAutoCloseable
import org.apache.commons.compress.archivers.{ArchiveOutputStream, ArchiveStreamFactory}
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.utils.IOUtils
object ZipHelper {
def getListByExtension(dir: String, extension: String): IO[List[File]] =
IO(new File(dir)).map { d =>
if (d.isDirectory) {
d.listFiles
.filter(_.isFile)
.filter(_.getName.endsWith(s".$extension"))
.toList
} else Nil
}
/**
*
* @param sourceFolder directory with file to zip
* @param destFolder destination zip file
* @param zipFileName the name of zip archive
* @param extension extension of files to zip in sourceFolder
* @return the complete path of zipped file
*/
def zipFiles(sourceFolder: String, destFolder: String, zipFileName: String, extension: String): IO[String] = {
def zipFileList(files: List[File], archive: ArchiveOutputStream): IO[Unit] = files.foldLeft(IO.unit) { (io, file) =>
io.flatMap { _ =>
println("Adding file to archive: " + file.getName)
archive.putArchiveEntry(new ZipArchiveEntry(file, file.getName))
fromAutoCloseable(IO(new FileInputStream(file))) use { x =>
IOUtils.copy(x, archive)
archive.closeArchiveEntry()
IO.unit
}
}
}
for {
_ <- IO(println(s"zipFiles sourceFolder: $sourceFolder destFolder: $destFolder zipFileName: $zipFileName extension: $extension"))
path <- IO(destFolder + "/" + zipFileName)
_ <- fromAutoCloseable(IO(new ArchiveStreamFactory().createArchiveOutputStream("zip", new FileOutputStream(path)))) use { archive =>
for {
l <- getListByExtension(sourceFolder, extension)
_ <- zipFileList(l, archive)
} yield ()
}
} yield path
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment