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()
@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