简体   繁体   中英

Adding 2 files to zip archive with Java

I need to put 2 files in one zip archive using java. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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