Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Last active July 2, 2018 16:29
Show Gist options
  • Save EdgeCaseBerg/427084e7472846ce6abee2b58c235724 to your computer and use it in GitHub Desktop.
Save EdgeCaseBerg/427084e7472846ce6abee2b58c235724 to your computer and use it in GitHub Desktop.
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