gpt4 book ai didi

java - 如何防止制作空的 zip 文件

转载 作者:行者123 更新时间:2023-11-30 03:46:13 24 4
gpt4 key购买 nike

我正在生成图像文件的 zip。但是,如果未找到图像,则会生成类似 java.util.zip.ZipException: ZIP file must have at least one Entry 的异常。我正在处理异常,但正在生成 0 大小的空 zip。所以请帮我解决这个问题

    try {
// create the ZIP file

ZipOutputStream out = getOutputStream(subpart, destinationZipPath);

/*
* ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
* destinationZipPath));
*/
// compress the files
LOGGER.error("zip creation is started @" + new Date().toString());
for (String fileNameDB : filesTobeZipped) {
// To check duplication of filename in zip creation
if (!filesHash.containsKey(fileNameDB)) {
filesHash.put(fileNameDB, fileNameDB);
File f = new File(sourceFolder + fileNameDB);
// to chk file is exists on physical location or not
if (f.exists()) {
if (fileCount >= batchFileLimit) {
out.close();
subpart++;
out = getOutputStream(subpart, destinationZipPath);
fileCount = 0;
// overallSize=0;
}
FileInputStream in = new FileInputStream(f);
// add ZIP entry to output stream
out.putNextEntry(new ZipEntry(f.getName()));
// transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// complete the entry
out.closeEntry();
in.close();
fileCount++;
} else {
}
}

}
// complete the ZIP file
out.close(); // Exception if fileCount=0;
return true;
// return zipfile;
} catch (IOException ex) {
return false;
}

最佳答案

您不能在检测到第一个现有文件后创建 ZIP 流吗?就像

ZipOutputStream out = null;

for (String fileNameDB : filesTobeZipped) {
if (new File(fileNameDB).exists()) {
if (out == null) {
out= ZipOutputStream out = getOutputStream(subpart, destinationZipPath);
}

// do other operations
}
}

关于java - 如何防止制作空的 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com