Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Commons Unzip method?

Tags:

java

zip

scala

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?

like image 906
Rex Butler Avatar asked May 19 '15 20:05

Rex Butler


People also ask

How do I unzip a zip file in Java?

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.

How can I read the content of a zip file without unzipping it in Java?

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.

What is Commons compress used for?

Apache Commons Compress software defines an API for working with compression and archive formats.


1 Answers

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);                          
                    }
                }
            }
        }
    }
}
like image 191
CQLI Avatar answered Sep 16 '22 15:09

CQLI