Create a zip consisting of multiple fileoutputStreams objects

69 Views Asked by At

I have a method in which in a loop I am creating FileOutputStream objects of excel files. Each file is in different folder as per the requirement. I need to create a zip response as well of the whole. Is there a way to add those fileoutputstream objects in the zipoutputstream( in the same loop, while the files are getting generated)?

Consider this as pseudo code

// For Loop creating Fileoutputstream
{
try (FileoutPutStream fileOut= new FileoutputStream(FilePath);
   workbook.write(fileOut);
   workbook.close();
///**add logic to add this file into zip.**
}

I have tried creating a zipoutputstream object and writing the content into the zip.entry() but it did not work. Plus i am confused as if this is possible or not?

1

There are 1 best solutions below

1
On

You can create a ZipFile and add them like this. file is an object of class File. ZipFile is imported from import net.lingala.zip4j.ZipFile;.

      try (ZipFile zipFile = new ZipFile("compressed.zip")) {
            zipFile.addFile(file, zipParameters);
        } catch (Exception e) {
            log.error("error during zipping of file");
            throw e;
        }

where zipParameters are

ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionLevel(CompressionLevel.NORMAL);