首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 多檔案壓縮為 ZIP 並輸出流:完整工具類實作

     編輯:Java 程式設計入門

應用場景

Web 下載多檔案打包、報表匯出、日志歸檔等場景,需將多個檔案壓縮為 ZIP 並以 ByteArrayOutputStream 形式回傳,後續可直接寫入 HTTP 響應或進行 MD5 校驗。

核心實作:fileToZip 方法

public ByteArrayOutputStream fileToZip(List<String> fileList, String zipName, String tempFilePath) {
    byte[] buffer = new byte[1024];
    ZipOutputStream out = null;
    try {
        // 1. 建立臨時 ZIP 檔
        out = new ZipOutputStream(new FileOutputStream(tempFilePath + zipName + ".zip"));
        List<File> files = new ArrayList<>();
        for (String path : fileList) {
            files.add(new File(path));
        }

        // 2. 逐個寫入 ZIP 條目
        for (File file : files) {
            try (FileInputStream fis = new FileInputStream(file)) {
                out.putNextEntry(new ZipEntry(file.getName()));
                int len;
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
            }
        }
        out.close();

        // 3. 讀取 ZIP 至記憶體流
        File zipFile = new File(tempFilePath + zipName + ".zip");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (FileInputStream fis = new FileInputStream(zipFile);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            int b;
            while ((b = bis.read()) != -1) {
                baos.write(b);
            }
        }
        return baos;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (out != null) try { out.close(); } catch (IOException ignored) {}
    }
}

Web 層調用範例(Servlet)

// 參數準備
String tempPath = "C:/temp/";
List<String> files = Arrays.asList(
    tempPath + "file1.txt",
    tempPath + "file2.png",
    tempPath + "file3.xls"
);
String zipName = "fileData";

// 取得壓縮流
ByteArrayOutputStream out = fileToZip(files, zipName, tempPath);
byte[] data = out.toByteArray();

// 寫入 HTTP 響應
response.reset();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", 
    "attachment;filename=" + new String("dataFile.zip".getBytes("GBK"), "ISO8859-1"));
response.addHeader("Content-Length", String.valueOf(data.length));
try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
    bos.write(data);
    bos.flush();
}

關鍵細節總結

環節注意點
編碼處理中文檔名需 GBK → ISO8859-1 轉碼,避免下載亂碼
資源釋放所有 Stream 必須在 finally 或 try-with-resources 中關閉
大檔案若總大小超過記憶體,建議改用 ServletOutputStream 邊壓縮邊輸出
臨時檔清理業務結束後應刪除 tempFilePath 下的臨時 ZIP

進階擴展

  • 支援目錄遞歸壓縮:遞歸遍歷 File.listFiles(),保留相對路徑
  • 加密 ZIP:引入 Zip4j 庫實現 AES 加密
  • 並行壓縮:大量檔案時可用 ForkJoinPool 分片處理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved