天天看點

Deflater 和 Inflater 在java中的用法以及注意的參數問題

項目中用到了這個壓縮和解壓縮的方式,與伺服器端的壓縮算法相對應,用戶端是android,資料壓縮後通過webservice傳遞到伺服器(php),一開始怎麼壓縮資料都無法再伺服器端解壓,一直困擾了很久,偶然間在國外的網站上找到一個說明,是建立對象的flag有true和false,分别對應兩個版本的協定,最後通用的(和php伺服器端的解壓縮對應)應該是把flag設定為true。下面代碼記錄了調用方式,需要注意建立兩個對象的參數。

壓縮端

    public static byte[] compressBytes(byte[] byteStr) {

ByteArrayInputStream bis = new ByteArrayInputStream(byteStr);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

try {

                        // 此處的第二個參數必須要設定成true,這樣才能成功與伺服器端對應壓縮與解壓縮(伺服器端對應的是php的解壓縮)

                       // 具體的原因是參照網上說的一個協定。參照位址以後會補發上來

Deflater def = new Deflater(Deflater.BEST_COMPRESSION,true);

DeflaterOutputStream dos = new DeflaterOutputStream(bos, def);

byte[] buf = new byte[1024];

int readCount = 0;

while ((readCount = bis.read(buf, 0, buf.length)) > 0) {

dos.write(buf, 0, readCount);

}

dos.close();

} catch (Exception ex) {

ex.printStackTrace();

}

byte[] res = bos.toByteArray();

return res;

}

 解壓縮

   public static byte[] decompressBytes(byte[] byteEncrypto) {

ByteArrayInputStream bis = new ByteArrayInputStream(byteEncrypto);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

                // 相對應的解壓縮的參數也要設定未true

Inflater inf = new Inflater(true);

InflaterInputStream iis = new InflaterInputStream(bis, inf);

int readCount = 0;

byte[] buf = new byte[1024];

try {

while ((readCount = iis.read(buf, 0, buf.length)) > 0) {

bos.write(buf, 0, readCount);

}

iis.close();

return bos.toByteArray();

} catch (ZipException e) {

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

  希望對用到的有點幫助,可能這個壓縮算法在國内用的比較少,中文網站一直沒找到有詳細解釋的。