美文网首页
java.util.zip.GZIP demo

java.util.zip.GZIP demo

作者: 等你足够强了再说吧 | 来源:发表于2021-09-05 12:39 被阅读0次

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

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;

/**
 * @author cheng.tang
 */
@Slf4j
public class ZipUtils {

    /**
     * 使用gzip进行压缩
     *
     * @param waitingEncodingTxt
     * @return
     */
    public static String gzip(String waitingEncodingTxt) throws IOException {
        if (StringUtils.isBlank(waitingEncodingTxt)) {
            return "";
        }
        GZIPOutputStream gzip = null;
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(out);
            gzip.write(waitingEncodingTxt.getBytes());
            return Base64.getEncoder().encodeToString(out.toByteArray());
        } catch (Exception e) {
            log.warn("{}", e.getMessage(), e);
            throw e;
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (Exception ignored) {
                }
            }
        }
    }

    /**
     * 使用gzip进行解压缩
     *
     * @param compressedTxt
     * @return
     */
    public static String gunzip(String compressedTxt) {
        if (StringUtils.isBlank(compressedTxt)) {
            return "";
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
        GZIPInputStream ginzip = null;
        try {
            byte[] compressed = Base64.getDecoder().decode(compressedTxt);
            in = new ByteArrayInputStream(compressed);
            ginzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int offset;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            return out.toString();
        } catch (IOException e) {
            log.warn("{}", e.getMessage(), e);
            return compressedTxt;
        } finally {
            if (ginzip != null) {
                try {
                    ginzip.close();
                } catch (IOException ignored) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }
    }


}

相关文章

网友评论

      本文标题:java.util.zip.GZIP demo

      本文链接:https://www.haomeiwen.com/subject/xldadltx.html