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

Java 多檔案壓縮為 ZIP 並輸出 ByteArrayOutputStream 範例

     編輯:Java 相關知識

前言

Web 應用常需將多個檔案打包成 ZIP 並直接以串流回應下載,無需落地儲存。本文示範使用 ZipOutputStream 壓縮多檔案至 ByteArrayOutputStream,再寫入 HTTP Response。

核心方法

public ByteArrayOutputStream filesToZip(List filePaths, String zipName, String baseDir) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ZipOutputStream zos = new ZipOutputStream(baos)) {
        for (String path : filePaths) {
            File file = new File(baseDir, path);
            try (FileInputStream fis = new FileInputStream(file)) {
                zos.putNextEntry(new ZipEntry(file.getName()));
                byte[] buf = new byte[1024];
                int len;
                while ((len = fis.read(buf)) > 0) zos.write(buf, 0, len);
                zos.closeEntry();
            }
        }
        zos.finish(); // 重要:完成 ZIP 結構
    } catch (IOException e) { e.printStackTrace(); }
    return baos;
}

Servlet 下載範例

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List files = Arrays.asList("file1.txt", "file2.png", "data.xls");
        ByteArrayOutputStream zipStream = filesToZip(files, "export.zip", "C:/temp/");

        resp.setContentType("application/zip");
        resp.setHeader("Content-Disposition", "attachment; filename=\"export.zip\"");
        resp.setContentLength(zipStream.size());

        try (OutputStream out = resp.getOutputStream()) {
            zipStream.writeTo(out);
        }
    }
}

關鍵點

  • zos.finish() 必須在關閉前呼叫,寫入中央目錄結構。
  • ByteArrayOutputStream 適合中小檔案;大檔案應直接寫入 resp.getOutputStream() 避免 OOM。
  • 檔名中文需處理編碼:URLEncoder.encode(name, "UTF-8")。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved