Search code examples
zipspring-batch

Spring Batch program to create the fixed size zip file


I have a design issue.I want to create a 10 MB zip files using spring batch. But not sure what value i can select for chunk size. chunk size is predetermined value. lets say i decide that that chunk size is 100. So i read 100 files and try to create a zip file. but what if zip file size reaches 10 MB by just including 99 files. What will happen to the remaining 1 file?

Regards, Raj


Solution

  • I had a similar use case. What I did was to create a service that creates zip files of a limited size (10MB). So for example if I had a 99 files that reaches the 10MB, the service split the zip in two parts: file_to_zip.zip and file_to_zip.z01

    public List<File> createSplitFile(List<String> resourcesToZip, String directory, Long maxFileSize, String zipFileName) {
        List<File> splitZipFiles = null;
        try {
            ZipFile zipFile = new ZipFile(directory + zipFileName);
            Iterator<String> iterator = resourcesToZip.iterator();
            List<File> filesToAdd = new ArrayList();
            while (iterator.hasNext()) {
                File file = new File(iterator.next());
                if (file.exists()) {
                    filesToAdd.add(file);
                }
            }
    
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(CompressionMethod.DEFLATE);
            parameters.setCompressionLevel(CompressionLevel.NORMAL);
    
            zipFile.createSplitZipFile(filesToAdd, parameters, true, maxFileSize);
            splitZipFiles = zipFile.getSplitZipFiles();
        } catch (ZipException e) {
            LOG.error("Exception trying to compress statement file '{}'", e.getMessage());
        }
        return splitZipFiles;
    }