Skip to content

Instantly share code, notes, and snippets.

@rjsvaljean
Last active July 6, 2016 20:35
Show Gist options
  • Select an option

  • Save rjsvaljean/97de6d735c97b1370965b74b34b1c1fc to your computer and use it in GitHub Desktop.

Select an option

Save rjsvaljean/97de6d735c97b1370965b74b34b1c1fc to your computer and use it in GitHub Desktop.
object Zip {
import java.io._
import java.util.zip._
import org.apache.commons.io.IOUtils
private val logger = LoggerFactory.getLogger(getClass)
private val BUFFER = 2048
def zip(inputDir: File): Option[File] = {
val zipFile = File.createTempFile("zippedArtifact", ".zip")
try {
val out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))
val files = getAllFiles(inputDir)
files.foreach { file =>
val origin = new BufferedInputStream(new FileInputStream(file), BUFFER)
out.putNextEntry(new ZipEntry(file.getPath))
IOUtils.copy(origin, out)
origin.close()
}
out.close()
Some(zipFile)
} catch {
case e: Exception =>
logger.error("Failure during ziping", e)
None
}
}
private def getAllFiles(inputDir: File) = {
def go(inputDir: File): Array[File] = {
require(inputDir.exists(), s"${inputDir.getAbsolutePath} does not exist")
inputDir.list().flatMap { child =>
val fullPathToChild = new File(inputDir.getPath + "/" + child)
if (fullPathToChild.isDirectory) go(fullPathToChild)
else Array(fullPathToChild)
}
}
go(new File("directory"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment