Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Java 的 Deflater 與 Inflater 實作 DEFLATE 壓縮與解壓縮

在資料傳輸的場景裡,大型檔案往往會拖慢整體效率,因此實務上常見的做法是先把檔案壓縮、再進行傳輸,接收端收到後還原即可。Java 標準庫的 java.util.zip 套件提供了 Deflater 與 Inflater 兩個類別,正好對應 DEFLATE 演算法的壓縮與解壓縮能力。以下就分享一組自行封裝的壓縮/解壓縮方法,並以檔案內容的處理為例說明,其中各方法的細節用法可直接查閱 JDK 的 API 文件。

先看解壓縮的部分。核心思路是把待還原的位元組灌入 Inflater,再迴圈呼叫 inflate 逐步取出資料,寫進 ByteArrayOutputStream,最後轉回位元組陣列:

/**
    *
    * @param inputByte
    * 待解壓縮的位元組陣列
    * @return 解壓縮後的位元組陣列
    * @throws IOException
    */
public static byte[] uncompress(byte[] inputByte) throws IOException {
    int len = 0;
    Inflater infl = new Inflater();
    infl.setInput(inputByte);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] outByte = new byte[1024];
    try {
        while (!infl.finished()) {
            // 解壓縮並將結果輸出到位元組串流 bos
              len = infl.inflate(outByte);
              if (len == 0) {
                  break;
              }
              bos.write(outByte, 0, len);
          }
          infl.end();
        } catch (Exception e) {
            //
        } finally {
          bos.close();
        }
        return bos.toByteArray();
    }

接著是壓縮。寫法與解壓縮幾乎對稱,改用 Deflater,記得在輸入完畢後呼叫 finish() 告知資料已經送完:

/**
    * 壓縮
    * @param inputByte 待壓縮的位元組陣列
    * @return 壓縮後的資料
    * @throws IOException
    */
public static byte[] compress(byte[] inputByte) throws IOException {
    int len = 0;
    Deflater defl = new Deflater();
    defl.setInput(inputByte);
    defl.finish();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] outputByte = new byte[1024];
    try {
        while (!defl.finished()) {
            // 壓縮並將結果輸出到位元組串流 bos
              len = defl.deflate(outputByte);
              bos.write(outputByte, 0, len);
        }
        defl.end();
    } finally {
        bos.close();
    }
    return bos.toByteArray();
}

最後用 main 把流程串起來:讀入檔案、壓縮、以 Base64 編碼方便在網路上傳遞,再解碼還原並寫回另一支檔案。之所以要經過 Base64,是因為壓縮後的位元組多半不是可列印字元,直接當文字傳輸容易出問題:

public static void main(String[] args) {
    try {
        FileInputStream fis = new FileInputStream("D:\\testdeflate.txt");
        int len = fis.available();
        byte[] b = new byte[len];
        fis.read(b);
        byte[] bd = compress(b);
        // 為了能在網路上傳輸,通常以 Base64 編碼
        String encodestr = Base64.encodeBase64String(bd);
        byte[] bi = uncompress(Base64.decodeBase64(encodestr));
        FileOutputStream fos = new FileOutputStream("D:\\testinflate.txt");
        fos.write(bi);
        fos.flush();
        fos.close();
        fis.close();
    } catch (Exception e) {
        //
    }
}

Copyright © Linux教程網 All Rights Reserved