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

Java 使用 Apache Ant Zip 實現 ZIP 文件解壓(支援中文編碼)

     編輯:Java 綜合教學

Java 解壓 ZIP 文件完整實現(解決中文亂碼)

JDK 內建 java.util.zip 對中文文件名支援不佳,實務上常改用 Apache Ant 提供的 org.apache.tools.zip 套件,可指定編碼(如 GBK、UTF-8)正確讀取條目名稱。

Maven 依賴

<dependency>
  <groupId>org.apache.ant</groupId>
  <artifactId>ant</artifactId>
  <version>1.10.14</version>
</dependency>

核心解壓代碼

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.io.*;
import java.util.Enumeration;

public class UnZipFiles {
    public static void main(String[] args) {
        String zipPath = "D:/test.zip";
        String destDir = "F:/unZipFiles/";

        File zipFile = new File(zipPath);
        try (ZipFile zf = new ZipFile(zipFile, "GBK")) {  // 指定編碼
            Enumeration entries = zf.getEntries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File outFile = new File(destDir, entry.getName());

                if (entry.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    outFile.getParentFile().mkdirs();
                    try (InputStream is = zf.getInputStream(entry);
                         FileOutputStream fos = new FileOutputStream(outFile)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
            }
            System.out.println("解壓完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

關鍵點說明

  • 編碼指定:new ZipFile(file, "GBK") 解決 Windows 建立的 ZIP 中文亂碼;Linux 環境常用 UTF-8。
  • 目錄處理:條目為目錄時僅 mkdirs();為文件時需先建立父目錄再寫入。
  • 資源管理:採用 try-with-resources 自動關閉流,避免洩漏。
  • 緩衝區大小:1024 bytes 足夠一般場景,大文件可調大至 8192。

常見問題排查

  1. 報 ZipException: Invalid header — 確認文件確為 ZIP 格式,非 RAR/7z。
  2. 解壓出的文件名仍是亂碼 — 嘗試切換編碼參數(GBK/UTF-8/CP437)。
  3. 大文件解壓慢 — 考慮使用 BufferedInputStream 包裝輸入流。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved