Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()
@aaron-small

This comment has been minimized.

Copy link

@aaron-small aaron-small commented Aug 29, 2018

👍

@elliottj

This comment has been minimized.

Copy link

@elliottj elliottj commented Mar 6, 2019

👍 Nice one thanks.

@izlo1dro1dan

This comment has been minimized.

Copy link

@izlo1dro1dan izlo1dro1dan commented Oct 30, 2019

nice)

@krmao

This comment has been minimized.

Copy link

@krmao krmao commented Apr 8, 2020

very good
but have some problem about unzip executable file such as aapt/kotlinc file can't be executed

Successfully started process 'command '~/.gradle/caches/jars-3/b904ae6b5680741fdcde1a177998dc6f/kotlinc/bin/kotlinc''
错误: 找不到或无法加载主类 org.jetbrains.kotlin.preloading.Preloader
...
FAILURE: Build failed with an exception.

using code below with AntBuilder which aapt/kotlinc file can be executed success

/**
     * https://relentlesscoding.com/2017/08/04/using-groovys-antbuilder-to-zip-and-unzip-files/
     * https://stackoverflow.com/questions/645847/unzip-archive-with-groovy
     * @param zipFileName
     * @param outputDir
     * @return
     */
    static boolean unzipV2(String zipFileName, String outputDir) {
        try {
            def ant = new AntBuilder()
            ant.unzip(
                    src: zipFileName,
                    dest: outputDir,
                    overwrite: "true"
            )
            return true
        } catch (Exception e) {
            e.printStackTrace()
            return false
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment