gpt4 book ai didi

java - 使用 Java 将 2 个文件添加到 zip 存档

转载 作者:行者123 更新时间:2023-11-30 06:52:41 25 4
gpt4 key购买 nike

我需要使用 java 将 2 个文件放入一个 zip 存档中。我使用以下代码,它适用于一个文件。当我用两个文件调用该方法时,它不会抛出任何异常,但结果我损坏了文件

    private File createZipFile(File[] files) throws IOException {

File zipFile = new File("D:\\zip.zip");

FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));

for (File file: files) {
BufferedInputStream bufferedInputStream = null;
byte data[] = new byte[1024];
FileInputStream fileInputStream = new FileInputStream(file.getAbsolutePath());
bufferedInputStream = new BufferedInputStream(fileInputStream, 1024);

ZipEntry entry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(entry);
int count;
while ((count = bufferedInputStream.read(data, 0, 1024)) != -1) {
zipOutputStream.write(data, 0, count);
}
bufferedInputStream.close();
fileInputStream.close();
}

zipOutputStream.close();

return zipFile;
}

最佳答案

看起来您在循环结束时缺少 zipOutputStream.closeEntry()

关于java - 使用 Java 将 2 个文件添加到 zip 存档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38503998/

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