Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to make a zip file in scala (Java 8)
import java.io.FileOutputStream
import java.nio.file.{Files, Paths, Path, FileVisitResult}
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.SimpleFileVisitor
def autoClosing[C <: Closeable, T](closeable: C)(c: C => T) = {
try {
c(closeable)
} finally {
closeable.close()
}
}
implicit class CloseableOps[C <: Closeable](resource: C) {
def map[B](f: C => B): B = autoClosing(resource)(f)
def flatMap[B](f: C => B): B = autoClosing(resource)(f)
}
def makeZip(directory: Path) {
import java.util.zip._
val zipName = directory.getFileName() + ".zip"
for {
fis <- new FileOutputStream(zipName)
zos <- new ZipOutputStream(fis)
} yield {
Files.walkFileTree(directory, new SimpleFileVisitor[Path] {
override def visitFile(path: Path, attrs: BasicFileAttributes): FileVisitResult = {
/* Add it to the zip file if its a file */
if (attrs.isRegularFile()) {
val zipEntryName = {
path.subpath(
directory.getNameCount(),
path.getNameCount() // subpath has an exclusive bound, so use getNameCount and not getNameCount - 1
).toString
}
println(s"Writing to zip: ${zipEntryName}")
val zipEntry = new ZipEntry(zipEntryName)
zos.putNextEntry(zipEntry)
val bytesToWrite = Files.readAllBytes(path)
zos.write(bytesToWrite, 0, bytesToWrite.size)
zos.closeEntry()
}
FileVisitResult.CONTINUE
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment