[Java基础]Java运用GZIP进行文本压缩

[Java基础]Java使用GZIP进行文本压缩
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.io.output.ByteArrayOutputStream;
//该ByteArrayOutputStream类比jdk的同类好!细看其javadoc:In contrast to the original it doesn't reallocate the whole memory block but allocates additional buffers. 

//(压缩都是基于字节码而非字符)
public class TextZip {

    public static void main(String[] args) throws IOException {

        byte[] bytes = "中文撒大撒大发送大大三大四大赛的温热她跟他中文撒大撒大发送大大大三送大大三大四大赛的温热她跟他中文撒大撒大发送大大大三大四大赛的温热她跟他中文撒大撒大发送大大三大四大赛的温热她跟他"
                .getBytes();
        //对bytes压缩
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(1024);
        GZIPOutputStream gzipOutput = new GZIPOutputStream(byteOutput, 1024);
        gzipOutput.write(bytes);
        gzipOutput.close();

        //验证一下压缩后的效果对比
        System.out.println(bytes.length);
        for (byte b : bytes) {
            System.out.print(b + " ");
        }
        System.out.println();

        byte[] bytes2 = byteOutput.toByteArray();
        System.out.println(bytes2.length);
        for (byte b : bytes2) {
            System.out.print(b + " ");
        }
    }

}

 

效果:

 

270


-28 -72 -83 -26 -106 -121 -26 -110 -110 -27 -92 -89 -26 -110 -110 -27 -92 -89 -27 -113 -111 -23 -128 -127 -27 -92 -89 -27 -92 -89 -28 -72 -119 -27 -92 -89 -27 -101 -101 -27 -92 -89 -24 -75 -101 -25 -102 -124 -26 -72 -87 -25 -125 -83 -27 -91 -71 -24 -73 -97 -28 -69 -106 -28 -72 -83 -26 -106 -121 -26 -110 -110 -27 -92 -89 -26 -110 -110 -27 -92 -89 -27 -113 -111 -23 -128 -127 -27 -92 -89 -27 -92 -89 -27 -92 -89 -28 -72 -119 -23 -128 -127 -27 -92 -89 -27 -92 -89 -28 -72 -119 -27 -92 -89 -27 -101 -101 -27 -92 -89 -24 -75 -101 -25 -102 -124 -26 -72 -87 -25 -125 -83 -27 -91 -71 -24 -73 -97 -28 -69 -106 -28 -72 -83 -26 -106 -121 -26 -110 -110 -27 -92 -89 -26 -110 -110 -27 -92 -89 -27 -113 -111 -23 -128 -127 -27 -92 -89 -27 -92 -89 -27 -92 -89 -28 -72 -119 -27 -92 -89 -27 -101 -101 -27 -92 -89 -24 -75 -101 -25 -102 -124 -26 -72 -87 -25 -125 -83 -27 -91 -71 -24 -73 -97 -28 -69 -106 -28 -72 -83 -26 -106 -121 -26 -110 -110 -27 -92 -89 -26 -110 -110 -27 -92 -89 -27 -113 -111 -23 -128 -127 -27 -92 -89 -27 -92 -89 -28 -72 -119 -27 -92 -89 -27 -101 -101 -27 -92 -89 -24 -75 -101 -25 -102 -124 -26 -72 -87 -25 -125 -83 -27 -91 -71 -24 -73 -97 -28 -69 -106


90


31 -117 8 0 0 0 0 0 0 0 123 -78 99 -19 -77 105 -19 -49 38 77 122 -70 100 57 -124 124 -38 63 -15 101 67 35 -120 -79 100 -7 -109 29 -99 32 -58 -20 -39 64 -14 -59 -42 -39 -49 103 -75 60 -37 -79 -14 121 -13 -38 -89 75 119 -66 -40 62 -1 -55 -18 105 79 -16 106 -121 -104 64 93 -45 40 49 -127 -96 118 0 -76 10 12 52 14 1 0 0