简体   繁体   中英

Apache Commons Unzip method?

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?

I don't know a package that does that. You need to write some code. It's not hard. I've not used that package, but it's easy to do in the JDK. Look at the ZipInputStream in the JDK. Use FileInputStream to open a file. Create a ZipInputStream from the FileInputStream and you can read the entries using getNextEntry. It's pretty easy really, but requires some code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM