Search code examples
javazipcompressiongzip

How put files into zip just for pack them and no compress them in Java


Is there way in Java to pack files into zip without compression? I just need to pack many files into one, but i need it fast and compression take long time. I tried something like Stored method of ZipOutputStream but the result zip is always corrupted. Does anybody know some solution?

EDIT: There is my code:

response.setContentType("application/zip"); // zip archive format
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
                                                                            .filename("download.zip", StandardCharsets.UTF_8)
                                                                            .build()
                                                                            .toString());
        
            response.setContentLengthLong(totalSize);
    
            try(ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
                zipOutputStream.setLevel(Deflater.NO_COMPRESSION);
            for (FileSystemResource file : resources) {
                try (InputStream inputStream = file.getInputStream()) {
                    zipOutputStream.putNextEntry(new ZipEntry(file.getFilename().toString()));
                    StreamUtils.copy(inputStream, zipOutputStream);
                    zipOutputStream.flush();
                }
            }
        }

it works normal but when i added:

zipOutputStream.setLevel(Deflater.NO_COMPRESSION);

i get this error when i try to open final zip: Could not open, ERROR 1 process doesnt exist

Zip wihtou level is always good


Solution

  • The problem is that you are setting the content length of the response to (presumably) the length of the file you are outputting. however, a zip file, even with no compression, still includes a header (or footer as the case may be). you either have to compute the length of the complete zip file, or use chunked encoding.