Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 2 files to zip archive with Java

Tags:

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;
    }
like image 746
Vadim Dissa Avatar asked Jul 27 '26 11:07

Vadim Dissa


1 Answers

It looks like you are missing zipOutputStream.closeEntry() at the end of your loop.

like image 128
noscreenname Avatar answered Jul 30 '26 01:07

noscreenname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!