Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Last active September 4, 2021 16:15
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save bitsnaps/00947f2dce66f4bbdabc67d7e7b33681 to your computer and use it in GitHub Desktop.
Save bitsnaps/00947f2dce66f4bbdabc67d7e7b33681 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
byte[] buffer = new byte[1024]
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName))
ZipEntry zipEntry = zis.getNextEntry()
while (zipEntry != null) {
File newFile = new File(outputDir+ File.separator, zipEntry.name)
if (zipEntry.isDirectory()) {
if (!newFile.isDirectory() && !newFile.mkdirs()) {
throw new IOException("Failed to create directory " + newFile)
}
} else {
// fix for Windows-created archives
File parent = newFile.parentFile
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Failed to create directory " + parent)
}
// write file content
FileOutputStream fos = new FileOutputStream(newFile)
int len = 0
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len)
}
fos.close()
}
zipEntry = zis.getNextEntry()
}
zis.closeEntry()
zis.close()
@aaron-small
Copy link

👍

@elliottj
Copy link

elliottj commented Mar 6, 2019

👍 Nice one thanks.

@izlo1dro1dan
Copy link

nice)

@krmao
Copy link

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
        }
    }

@tadeubas
Copy link

The unzip process is broken, it gives only part of the file bytes, to fix this issue I used a java.nio.file.*:

import java.nio.file.*

//UnZip archive

def zip = new ZipFile(new File(outputDir + 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()

    InputStream is = zip.getInputStream(it);
    Files.copy(is, fOut.toPath(), StandardCopyOption.REPLACE_EXISTING);
  }
}
zip.close()

@bitsnaps
Copy link
Author

The unzip process is broken, it gives only part of the file bytes, to fix this issue I used a java.nio.file.*

It should be now fixed, the standard java.util.zip can handle it, no need to use java.nio.file.*, credits to @Baeldung.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment