Last active
September 4, 2021 16:15
-
-
Save bitsnaps/00947f2dce66f4bbdabc67d7e7b33681 to your computer and use it in GitHub Desktop.
Zip and UnZip files using Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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
The unzip process is broken, it gives only part of the file bytes, to fix this issue I used a
java.nio.file.*
: