Java Util:Zip批量下载&文件打包

        在项目开发中,经常会遇到文件下载、导出的功能,导出文件格式包括.xls、.pdf等,对于单个的文件下载,只需要执行excel和pdf的导出即可;但有时会碰到多个excel或pdf文件的批量下载,且执行文件要压缩到一个文件中,这时就要用到Zip文件压缩的功能了;

 如下是自己封装的一个ZipFileUtil工具类,支持mvc模式下excel和pdf文件的ZIP文件打包和下载:

public class ZipFileUtil {
    private static ZipOutputStream outputStream;

    private ZipFileUtil() {
        // prevent construct
    }

    public static void setZipOutputStream(HttpServletResponse response, String zipName) throws IOException {
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(zipName.concat(".zip"), "UTF-8"));

        outputStream = new ZipOutputStream(response.getOutputStream());
    }

    public static void excelToZipEntry(SXSSFWorkbook workbook, String excelName) throws IOException {
        File tmpFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx");
        boolean deleted;

        try (FileOutputStream os = new FileOutputStream(tmpFile);
                FileInputStream fileInputStream = new FileInputStream(tmpFile);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {

            workbook.write(os);

            ZipEntry entry = new ZipEntry(excelName + ".xlsx");
            outputStream.putNextEntry(entry);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

        } finally {
            outputStream.closeEntry();
            deleted = tmpFile.delete();
        }

        if (!deleted) {
            throw new IOException("Could not delete temporary file after processing: " + tmpFile);
        }
    }

    public static void pdfToZipEntry(String pdfFileName, byte[] bytes) throws IOException {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            ZipEntry entry = new ZipEntry(pdfFileName + ".pdf");
            outputStream.putNextEntry(entry);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = byteArrayInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

        } finally {
            outputStream.closeEntry();
        }
    }

    public static void closeZipOutputStream() throws IOException {
        outputStream.close();
    }
}

 

你可能感兴趣的:(java,util,java,io)