zipping files in java memory produces a zip file but the files inside are empty

Stack Overflow Asked by Tanoy Majumdar on December 16, 2020

I am trying to zip multiple files in Java to be used in my jar. 2 files are images and 1 is an HTML temp file. Upon zipping these files, when I try to see the contents of the zip file, all 3 files have become empty. There is no error being thrown as the files are in the zip but they are empty for some reason. I need to save my zip file in memory.

Here is my zip code.

public static File zipPdf(File data, File cover) throws IOException {

    ArrayList<ByteArrayOutputStream> zips = new ArrayList<>();
    ClassLoader loader = RunningPDF.class.getClassLoader();
    File image = new File(Objects.requireNonNull(loader.getResource("chekklogo.png")).getFile());

    File man = new File(Objects.requireNonNull(loader.getResource("manlogo.jpg")).getFile());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try(ZipOutputStream zos = new ZipOutputStream(baos)) {
        ZipEntry entry = new ZipEntry(data.getName());

        ZipEntry entry2 = new ZipEntry(image.getName());

        ZipEntry entry3 = new ZipEntry(man.getName());

    } catch(IOException ioe) {

One Answer

You forget to write the bytes. The putNextEntry just adds an entry. You need to explicitly write the bytes. Go with the following

        File file = new File(filePath);
        String zipFileName = file.getName().concat(".zip");

        FileOutputStream fos = new FileOutputStream(zipFileName);
        ZipOutputStream zos = new ZipOutputStream(fos);

        zos.putNextEntry(new ZipEntry(file.getName()));

        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        zos.write(bytes, 0, bytes.length);

Correct answer by user123 on December 16, 2020

Add your own answers!

Related Questions

Serialise array as single XML element in C#

1  Asked on January 25, 2021 by david-poxon


How to Create a Function to extract data from a JSON file

1  Asked on January 25, 2021 by ineedhelp


SQL create aggregated result from 2 queries

2  Asked on January 25, 2021 by sudhishkr


Mongoose : find document with subdocument filter

1  Asked on January 25, 2021 by temp_user


problems with @binding between structs

1  Asked on January 24, 2021 by mateus-neves


Testing Saga using Jest that have other module dependencies

0  Asked on January 24, 2021 by mzafer


mysql join 3 table but the “COUNT” be duplicate

1  Asked on January 24, 2021 by faisal-budiman


FTPS failing, but only on some commands on some machines

1  Asked on January 24, 2021 by watyf


Differently displayed colors on chart.js

3  Asked on January 24, 2021 by leos-literak


Vue Js Dynamic Class Binding Not Updating

2  Asked on January 24, 2021 by niall-parker


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP