java实现多个流文件压缩导出工具类

public static void export(HttpServletResponse response, Map<String, InputStream> streamsMap, String zipFileName) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream);
    try {
        byte[] buffer = new byte[1024];
        for (Map.Entry<String, InputStream> entry : streamsMap.entrySet()) {
            String entryName = entry.getKey();
            InputStream in = entry.getValue();
            zipOut.putNextEntry(new ZipEntry(entryName));
            int len;
            while ((len = in.read(buffer)) > 0) {
                zipOut.write(buffer, 0, len);
            }
            in.close();
        }
        zipOut.finish();

        byte[] bytes = byteArrayOutputStream.toByteArray();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + "\"");
        response.setContentLength(bytes.length);

        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
    } finally {
        if (zipOut != null) {
            zipOut.close();
        }
    }
}
Map<String, InputStream> streamsMap = new HashMap<>();
streamsMap.put("file1.txt", new FileInputStream("file1.txt"));
streamsMap.put("file2.txt", new FileInputStream("file2.txt"));
MultiStreamZipExporter.export(response, streamsMap, "output.zip");

你可能感兴趣的:(功能集合,java,开发语言)