我正在尝试在 Azure blob 中压缩文件。我可以使用正常的 zip 方法创建 zip 文件,但为了提高性能,当我尝试使用 completable future 时,我遇到了异常。
try (ZipOutputStream zipStream = new ZipOutputStream(outputStream)) {
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (String singleFileName : fileNames) {
String singleFilePath = azureFilePath + "/" + singleFileName.trim();
BlobClient blobClient = blobContainerClient.getBlobClient(singleFilePath);
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try (ByteArrayOutputStream fileOutputStream = new ByteArrayOutputStream()) {
if (blobClient.exists()) {
// Download the file to a separate output stream
blobClient.download(fileOutputStream);
// Add the file to the zip stream
zipStream.putNextEntry(new ZipEntry(singleFileName));
zipStream.write(fileOutputStream.toByteArray());
// zipStream.closeEntry();
} else {
throw new RuntimeException("File not found: " + singleFilePath);
}
} catch (IOException e) {
throw new RuntimeException("Error processing file: " + singleFileName, e);
}finally {
try {
zipStream.closeEntry();
} catch (IOException e) {
// Handle any potential exception when closing the zip entry
e.printStackTrace();
}
}
});
futures.add(future);
}
CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allOf.join();
}
// Upload the zip file to the same location
BlobClient zipFileClient = blobContainerClient.getBlobClient(azureFilePath + "/" + zipFileName);
zipFileClient.upload(new ByteArrayInputStream(outputStream.toByteArray()), outputStream.size(),true);
抛出异常 zipStream.write(fileOutputStream.toByteArray());
java.util.zip.ZipException: no current ZIP entry
at java.base/java.util.zip.ZipOutputStream.write(ZipOutputStream.java:343) ~[na:na]
at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:108) ~[na:na]
at main.java.com.azure.filezip.ApiControllerzip.lambda$uploadZip$0(ApiControllerzip.java:78) ~[classes/:na]
有什么建议吗?