All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kaizen4j.common.encrypt.GZIP Maven / Gradle / Ivy

package org.kaizen4j.common.encrypt;

import com.google.common.base.Throwables;

import java.io.*;
import java.util.Objects;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * GZIP压缩类
 */
public final class GZIP {

    private GZIP() {}

    /**
     * GZIP 压缩
     *
     * @param str 待压缩字符串
     * @return 压缩后的字节数组
     *
     * @throws IOException
     */
    public static byte[] compress(String str) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);

            byte[] bytes = str.getBytes(UTF_8);
            gzipOutputStream.write(bytes, 0, bytes.length);
            gzipOutputStream.finish();
            gzipOutputStream.flush();
            gzipOutputStream.close();

            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * GZIP 解压
     *
     * @param bytes 待解压的字节数组
     * @return 解压后的字符串
     *
     * @throws IOException
     */
    public static String decompress(byte[] bytes) {
        try {
            GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(bytes));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gzipInputStream, UTF_8));

            StringBuffer content = new StringBuffer();
            String line;
            while (Objects.nonNull(line = bufferedReader.readLine())) {
                content.append(line);
            }
            return content.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy