Apache Commons解压方法?

Tho*_*lem 6 java zip scala

我最近发现了https://commons.apache.org/proper/commons-compress/zip.html,Apache Commons Compress 库。

但是,没有直接的方法可以简单地将给定文件解压缩到特定目录。

有没有规范/简单的方法来做到这一点?

CQL*_*QLI 7

一些使用 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);                          
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 2

我不知道有哪个软件包可以做到这一点。您需要编写一些代码。这并不难。我没有使用过这个包,但是在 JDK 中很容易做到。查看JDK中的ZipInputStream 。使用 FileInputStream 打开文件。从 FileInputStream 创建 ZipInputStream,您可以使用 getNextEntry 读取条目。这确实很简单,但需要一些代码。

  • 最好使用 ZipFile。与 ZipInputStream 相比,使用 ZipFile 的主要好处是它使用随机访问来迭代不同的条目,而 ZipInputStream 是顺序的,因为它与流一起使用,因此它无法自由移动位置。 (2认同)