在 JSP 頁面中呼叫 Java 方法,將指定目錄遞歸壓縮為 ZIP 檔案,支援 Linux/Windows,處理編碼與大檔案流式寫入。
<%@ page import="java.io.*, java.util.zip.*, javax.servlet.jsp.JspWriter" %>
<%
// 壓縮入口方法
public void zip(String zipPath, String srcPath, JspWriter out) throws Exception {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
zipEntry(zos, srcPath, srcPath, zipPath);
out.print("ZIP 壓縮成功:" + zipPath);
} catch (Exception e) {
out.print("壓縮失敗:" + e.getMessage());
e.printStackTrace();
} finally {
if (zos != null) try { zos.close(); } catch (IOException ignored) {}
}
}
// 遞歸添加 ZIP 條目
public void zipEntry(ZipOutputStream zos, String basePath, String filePath, String zipPath) throws Exception {
File file = new File(filePath);
if (file.isDirectory()) {
String[] children = file.list();
if (children != null) {
for (String child : children) {
zipEntry(zos, basePath, filePath + File.separator + child, zipPath);
}
}
return;
}
// 計算 ZIP 內部相對路徑(去除基礎路徑前綴)
String entryName = filePath.substring(basePath.length() + 1);
// 統一使用正斜線,相容跨平台解壓
entryName = entryName.replace(File.separatorChar, '/');
// 避免將輸出的 ZIP 檔自己也壓縮進去
if (file.getAbsolutePath().equals(new File(zipPath).getAbsolutePath())) return;
ZipEntry entry = new ZipEntry(entryName);
entry.setSize(file.length());
entry.setTime(file.lastModified());
zos.putNextEntry(entry);
// 流式讀寫,避免大檔案 OOM
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
byte[] buffer = new byte[8192];
int len;
while ((len = bis.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
}
%>
<%
String srcDir = application.getRealPath("/WEB-INF/export/data");
String zipFile = application.getRealPath("/WEB-INF/export/data_backup.zip");
zip(zipFile, srcDir, out);
%>
| 技術點 | 處理方式 |
|---|---|
| 編碼問題 | ZIP 標準不指定編碼,建議檔名僅用 ASCII;若需中文檔名,需使用 Zip4j 或 Apache Commons Compress 指定 UTF-8 編碼。 |
| 大檔案支援 | 使用 8KB 緩衝區流式讀寫,不將整個檔案載入記憶體。 |
| 空目錄處理 | 遞歸時 file.list() 回傳 null 需防呆。 |
| 路徑分隔符 | 統一轉為 /,確保跨平台解壓一致性。 |
| 排除輸出檔 | 比對絕對路徑避免自我壓縮導致無限遞歸。 |
<!-- Maven 依賴 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.26.0</version>
</dependency>
// 使用 Commons Compress(支援 UTF-8 檔名、大檔案、多執行緒)
try (ArchiveOutputStream out = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", new FileOutputStream(zipFile))) {
out.putArchiveEntry(new ZipArchiveEntry(entryName));
Files.copy(file.toPath(), out);
out.closeArchiveEntry();
}
../../etc/passwd)。