Skip to content

Instantly share code, notes, and snippets.

@krmao
Forked from bitsnaps/ZipUnzip.groovy
Created April 8, 2020 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krmao/4223ec0d2e871eace21ce0f6e1c579f7 to your computer and use it in GitHub Desktop.
Save krmao/4223ec0d2e871eace21ce0f6e1c579f7 to your computer and use it in GitHub Desktop.
Zip and UnZip files using Groovy
import java.util.zip.*
String zipFileName = "file.zip"
String inputDir = "logs"
def outputDir = "zip"
//Zip files
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName))
new File(inputDir).eachFile() { file ->
//check if file
if (file.isFile()){
zipFile.putNextEntry(new ZipEntry(file.name))
def buffer = new byte[file.size()]
file.withInputStream {
zipFile.write(buffer, 0, it.read(buffer))
}
zipFile.closeEntry()
}
}
zipFile.close()
//UnZip archive
def zip = new ZipFile(new File(zipFileName))
zip.entries().each{
if (!it.isDirectory()){
def fOut = new File(outputDir+ File.separator + it.name)
//create output dir if not exists
new File(fOut.parent).mkdirs()
def fos = new FileOutputStream(fOut)
//println "name:${it.name}, size:${it.size}"
def buf = new byte[it.size]
def len = zip.getInputStream(it).read(buf) //println zip.getInputStream(it).text
fos.write(buf, 0, len)
fos.close()
}
}
zip.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment