首页 > 编程语言 > 详细

java 实现PHP gzcompress 功能

时间:2020-01-01 09:18:25      阅读:103      评论:0      收藏:0      [点我收藏+]

为了直观加了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=

java 实现PHP gzcompress 功能

原文:https://www.cnblogs.com/glory-jzx/p/12127929.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!