I've recently discovered https://commons.apache.org/proper/commons-compress/zip.html, the Apache Commons Compress library.
However, there is no direct method to simply unzip a given file to a particular directory.
Is there a canonical / easy way to do this?
To unzip a zip file, we need to read the zip file with ZipInputStream and then read all the ZipEntry one by one. Then use FileOutputStream to write them to file system. We also need to create the output directory if it doesn't exists and any nested directories present in the zip file.
Methods. getComment(): String – returns the zip file comment, or null if none. getEntry(String name): ZipEntry – returns the zip file entry for the specified name, or null if not found. getInputStream(ZipEntry entry) : InputStream – Returns an input stream for reading the contents of the specified zip file entry.
Apache Commons Compress software defines an API for working with compression and archive formats.
Some sample code using IOUtils:
public static void unzip(Path path, Charset charset) throws IOException{
String fileBaseName = FilenameUtils.getBaseName(path.getFileName().toString());
Path destFolderPath = Paths.get(path.getParent().toString(), fileBaseName);
try (ZipFile zipFile = new ZipFile(path.toFile(), ZipFile.OPEN_READ, charset)){
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
Path entryPath = destFolderPath.resolve(entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(entryPath);
} else {
Files.createDirectories(entryPath.getParent());
try (InputStream in = zipFile.getInputStream(entry)){
try (OutputStream out = new FileOutputStream(entryPath.toFile())){
IOUtils.copy(in, out);
}
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With