简体   繁体   English

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

[英]Adding 2 files to zip archive with Java

I need to put 2 files in one zip archive using java.我需要使用 java 将 2 个文件放在一个 zip 存档中。 I use the following code and it works fine with one file.我使用以下代码,它适用于一个文件。 When I call the method with two files it doesn't throw any exception but I have broken file as a result当我用两个文件调用该方法时,它不会抛出任何异常,但结果我破坏了文件

    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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM