Search code examples
javamavenjarzip

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


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());
        zos.putNextEntry(entry);

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

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


    } catch(IOException ioe) {
        ioe.printStackTrace();
    }

Solution

  • 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);
            zos.closeEntry();
            zos.close();