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

时间:2016-07-21 12:13:45

标签: java

我需要使用java将2个文件放在一个zip存档中。我使用下面的代码,它可以正常使用一个文件。当我用两个文件调用该方法时,它不会抛出任何异常,但是我已经破坏了文件

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

        Random random = new Random();
        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;
    }

1 个答案:

答案 0 :(得分:4)

看起来你在循环结束时遗漏了zipOutputStream.closeEntry()