public class Compress {
public static void unzipWithCommons(File zipFile, String dest) throws IOException {
try (ZipFile archive = new ZipFile(zipFile)) {
for (ZipArchiveEntry entry : Collections.list(archive.getEntries())) {
File entryDestination = new File(dest, entry.getName());
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
Files.copy(archive.getInputStream(entry), entryDestination.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
public static void unzipWithCommonsAndCompletableFutures(File zipFile, String dest) throws IOException {
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
long startTime = System.nanoTime();
try (ZipFile archive = new ZipFile(zipFile)) {
List<ZipArchiveEntry> entries = Collections.list(archive.getEntries());
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(
entries.stream()
.map(entry -> CompletableFuture.runAsync(() -> {
File entryDestination = new File(dest, entry.getName());
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
// 确保父目录存在
try {
Files.createDirectories(entryDestination.toPath().getParent());
} catch (IOException e1) {
e1.printStackTrace();
}
try (InputStream in = archive.getInputStream(entry);
OutputStream out = Files.newOutputStream(entryDestination.toPath(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
throw new RuntimeException("Error extracting file: " + entry.getName(), e);
}
}
}, executor))
//方法将流中的所有 CompletableFuture 对象收集到一个新的数组中。这里的 CompletableFuture<?>[]::new 是一个构造函数引用,表示新数组应该是一个 CompletableFuture 类型的数组,并且根据实际需要自动分配合适的大小。
.toArray(CompletableFuture<?>[]::new)
);
// 等待所有任务完成
combinedFuture.join();
// 计算和输出执行时间
long endTime = System.nanoTime();
Duration duration = Duration.ofNanos(endTime - startTime);
System.out.printf("Unzipping completed in %s%n", duration.toString());
}
}
public static void main(String[] args) throws Exception {
unzipWithCommonsAndCompletableFutures(new File("C:\\abc\\merged-tomcat.zip"), "C:\\abc\\");
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/200885.html