JAVA中的deflate壓縮實現方法_java

來源:互聯網
上載者:User

在檔案的傳輸過程中,為了使大檔案能夠更加方便快速的傳輸,一般採用壓縮的辦法來對檔案壓縮後再傳輸,JAVA中的java.util.zip包中的Deflater和Inflater類為使用者提供了DEFLATE演算法的壓縮功能,以下是自已編寫的壓縮和解壓縮實現,並以壓縮檔內容為例說明,其中涉及的具體方法可查看JDK的API瞭解說明。

/**   *    * @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();  }  /**   * 壓縮.   *    * @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();  }  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) {      //    }  }

以上這篇JAVA中的deflate壓縮實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.