zoukankan      html  css  js  c++  java
  • java 实现PHP gzcompress 功能

    为了直观加了base64 

    PHP 代码:

    <?php
    $a = gzcompress("abc");
    echo base64_encode($a); 
    //输出: eJxLTEoGAAJNASc=
    解码:gzuncompress();

    源码提示默认使用的是 zlib的  deflate 进行编码的;

    function gzcompress ($data, $level = -1, $encoding = ZLIB_ENCODING_DEFLATE) {}

    对应的 JAVA处理代码 (JDK1.8):

    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Base64;
    import java.util.zip.Deflater;
    import java.util.zip.Inflater;
    
    public class GzCompress{
        public static void main(String[] args) {
    
            String encodeCompressd  = "eJxLTEoGAAJNASc=";
            byte[] compressd = Base64.getDecoder().decode( encodeCompressd );
            String origin  = new String( decompress(compressd) );
            System.out.println("origin: "+origin);
            byte[] _compressd = compress(origin.getBytes());
            byte[] _encodeCompress = Base64.getEncoder().encode(_compressd);
            System.out.println(new String(_encodeCompress));
        }
    
        public static byte[] decompress(byte[] data)  {
    
            byte[] output = new byte[0];
    
            Inflater decompresser = new Inflater();
            decompresser.reset();
            decompresser.setInput(data);
    
            ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
            try {
                byte[] buf = new byte[1024];
                while (!decompresser.finished()) {
                    int i = decompresser.inflate(buf);
                    o.write(buf, 0, i);
                }
                output = o.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    o.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            decompresser.end();
            return output;
        }
    
        public static byte[] compress( byte[] bytes ){
    
            byte[] output = new byte[1024];
            Deflater compresser = new Deflater();
            compresser.setInput(bytes);
            compresser.finish();
            int compressedDataLength = compresser.deflate(output);
            return Arrays.copyOf(output,compressedDataLength);
        }
    }

    对应输出:

    origin: abc
    compressLength:11
    eJxLTEoGAAJNASc=

  • 相关阅读:
    Python装饰器的解包装(unwrap)
    《Python cookbook》 “定义一个属性可由用户修改的装饰器” 笔记
    关于Python的函数(Method)与方法(Function)
    判断python对象是否可调用的三种方式及其区别
    tornado返回指定的http code
    Mac下安装pymssql
    iptables
    OpenFlow通信流程解读
    Prometheus的架构及持久化
    ansible总结
  • 原文地址:https://www.cnblogs.com/glory-jzx/p/12127929.html
Copyright © 2011-2022 走看看