Pack CSV files in ZIP Archive

by GarciaPL on Saturday 5 March 2016

This time I would like to share with small snippet of code written in Java and Spring MVC which might allow you to pack and download some files (in this case .csv file) in ZIP archive. So, if you will hit URL http://localhost:8090/yourApp/download/zip, Zip archive will be downloaded with name 'download.zip'.

    @ResponseBody
    @RequestMapping(value = {"/download/zip"}, method = RequestMethod.GET)
    public void downloadZipArchive(HttpServletResponse response) throws IOException {

        List<MyClass> list; //should contains some records!
        if (list != null && !list.isEmpty()) {
            if (list.size() > 200000) {

                response.setContentType("application/zip");
                response.addHeader("Content-Disposition", "attachment; filename=\"download.zip\"");
                response.addHeader("Content-Transfer-Encoding", "binary");

                OutputStream servletOutputStream = response.getOutputStream();
                ZipOutputStream zos = new ZipOutputStream(servletOutputStream);

                int counter = 0;
                List<List<MyClass>> dividedlist = Lists.partition(list, 200000);
                for (List<MyClass> partition : dividedlist) {
                    zos.putNextEntry(new ZipEntry("file_" + counter + ".csv"));
                    CSVWriter writer = new CSVWriter(new OutputStreamWriter(zos));
                    writer.writeNext(new String[]{"HEADER"});
                    for (MyClass item : partition) {
                        writer.writeNext(new String[]{item.getText()});
                    }
                    writer.flush();
                    zos.closeEntry();
                    counter++;
                }
                zos.close();
                response.getOutputStream().flush();
                response.getOutputStream().close();
            }
        }
    }