package com.fdkankan.reg;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
 * CompressionUtil 压缩字符串
 */
public class CompressionUtil {

    public static String compressAndEncode(String data) throws IOException {
        byte[] input = data.getBytes("UTF-8");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
        gzipOutputStream.write(input);
        gzipOutputStream.close();
        byte[] compressed = outputStream.toByteArray();
        byte[] encoded = Base64.getEncoder().encode(compressed);
        return new String(encoded, "UTF-8");
    }

    public static String decodeAndDecompress(String encodedData) throws IOException {
        byte[] encoded = encodedData.getBytes("UTF-8");
        byte[] compressed = Base64.getDecoder().decode(encoded);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(compressed);
        GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = gzipInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        gzipInputStream.close();
        return new String(outputStream.toByteArray(), "UTF-8");
    }
}