Apache Commons解压缩方法?
Apache Commons Unzip method?
我最近发现了 https://commons.apache.org/proper/commons-compress/zip.html,Apache Commons Compress 库。
但是,没有直接的方法可以简单地将给定文件解压缩到特定目录。
是否有规范/简单的方法来做到这一点?
我不知道有哪个软件包可以做到这一点。你需要写一些代码。这并不难。我没用过那个包,但在 JDK 中很容易做到。查看 JDK 中的 ZipInputStream。使用 FileInputStream 打开一个文件。从 FileInputStream 创建一个 ZipInputStream,您可以使用 getNextEntry 读取条目。这真的很简单,但需要一些代码。
一些使用 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);
}
}
}
}
}
}
我最近发现了 https://commons.apache.org/proper/commons-compress/zip.html,Apache Commons Compress 库。
但是,没有直接的方法可以简单地将给定文件解压缩到特定目录。
是否有规范/简单的方法来做到这一点?
我不知道有哪个软件包可以做到这一点。你需要写一些代码。这并不难。我没用过那个包,但在 JDK 中很容易做到。查看 JDK 中的 ZipInputStream。使用 FileInputStream 打开一个文件。从 FileInputStream 创建一个 ZipInputStream,您可以使用 getNextEntry 读取条目。这真的很简单,但需要一些代码。
一些使用 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);
}
}
}
}
}
}