为了直观加了base64
PHP 代码:
1<?php 2$a = gzcompress("abc"); 3echo base64_encode($a); 4 5//输出: eJxLTEoGAAJNASc= 6 7解码:gzuncompress();
源码提示默认使用的是 zlib的 deflate 进行编码的;
function gzcompress ($data, $level = -1, $encoding = ZLIB_ENCODING_DEFLATE) {}
对应的 JAVA处理代码 (JDK1.8):
1import java.io.ByteArrayOutputStream; 2import java.io.IOException; 3import java.util.Arrays; 4import java.util.Base64; 5import java.util.zip.Deflater; 6import java.util.zip.Inflater; 7 8public class GzCompress{ 9 public static void main(String[] args) { 10 11 String encodeCompressd = "eJxLTEoGAAJNASc="; 12 byte[] compressd = Base64.getDecoder().decode( encodeCompressd ); 13 String origin = new String( decompress(compressd) ); 14 System.out.println("origin: "+origin); 15 byte[] _compressd = compress(origin.getBytes()); 16 byte[] _encodeCompress = Base64.getEncoder().encode(_compressd); 17 System.out.println(new String(_encodeCompress)); 18 } 19 20 public static byte[] decompress(byte[] data) { 21 22 byte[] output = new byte[0]; 23 24 Inflater decompresser = new Inflater(); 25 decompresser.reset(); 26 decompresser.setInput(data); 27 28 ByteArrayOutputStream o = new ByteArrayOutputStream(data.length); 29 try { 30 byte[] buf = new byte[1024]; 31 while (!decompresser.finished()) { 32 int i = decompresser.inflate(buf); 33 o.write(buf, 0, i); 34 } 35 output = o.toByteArray(); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } finally { 39 try { 40 o.close(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 decompresser.end(); 46 return output; 47 } 48 49 public static byte[] compress( byte[] bytes ){ 50 51 byte[] output = new byte[1024]; 52 Deflater compresser = new Deflater(); 53 compresser.setInput(bytes); 54 compresser.finish(); 55 int compressedDataLength = compresser.deflate(output); 56 return Arrays.copyOf(output,compressedDataLength); 57 } 58}
对应输出:
origin: abc
compressLength:11
eJxLTEoGAAJNASc=