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

Java 實現 zip、gzip、7z、zlib 多種壓縮格式打包

     編輯:Java 相關知識

Maven 依賴

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.12</version>
</dependency>

格式對比

格式特點適用場景
zip多文件、目錄結構、跨平台通用打包分發
gzip單文件、高壓縮比、配合 tarLinux 日誌、傳輸
7z最高壓縮比、支持大文件備份、存檔
zlib數據流壓縮、無文件頭網絡傳輸、內存壓縮

核心工具類

public class CompressUtils {
    // zip 多文件
    public static void zip(String inputPaths, String output, String entryName) throws Exception {
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(output))) {
            for (String path : inputPaths.split("\\|")) {
                try (FileInputStream in = new FileInputStream(path)) {
                    out.putNextEntry(new ZipEntry(entryName != null ? entryName : new File(path).getName()));
                    copy(in, out);
                    out.closeEntry();
                }
            }
        }
    }

    // gzip 單文件
    public static void gzip(String input, String output, String entryName) throws Exception {
        try (GzipCompressorOutputStream out = new GzipCompressorOutputStream(
                new FileOutputStream(output), new GzipParameters().setFilename(entryName));
             FileInputStream in = new FileInputStream(input)) {
            copy(in, out);
        }
    }

    // 7z 多文件
    public static void sevenZ(String inputPaths, String output, String entryName) throws Exception {
        try (SevenZOutputFile out = new SevenZOutputFile(new File(output))) {
            for (String path : inputPaths.split("\\|")) {
                SevenZArchiveEntry entry = out.createArchiveEntry(new File(path),
                        entryName != null ? entryName : new File(path).getName());
                out.putArchiveEntry(entry);
                try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(path))) {
                    copy(in, out);
                }
                out.closeArchiveEntry();
            }
        }
    }

    // zlib 數據流
    public static void zlib(String input, String output) throws Exception {
        try (DeflateCompressorOutputStream out = new DeflateCompressorOutputStream(
                new FileOutputStream(output), new DeflateParameters().setWithZlibHeader(true));
             FileInputStream in = new FileInputStream(input)) {
            copy(in, out);
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
    }
}

選型建議

  • 需目錄結構、跨平台解壓 → zip
  • 單文件最大壓縮 → gzip / 7z
  • 網絡流/內存數據壓縮 → zlib
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved