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

com.jl.JsonZipUtils Maven / Gradle / Ivy

The newest version!
package com.jl;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * json压缩工具
 */
@Slf4j
public class JsonZipUtils {

    /**
     * 压缩
     *
     * @param unzip
     * @return
     */
    public static String zipString(String unzip) {
        // 0 ~ 9 压缩等级 低到高
        Deflater deflater = new Deflater(9);
        deflater.setInput(unzip.getBytes());
        deflater.finish();
        final byte[] bytes = new byte[256];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
        while (!deflater.finished()) {
            int length = deflater.deflate(bytes);
            outputStream.write(bytes, 0, length);
        }
        deflater.end();
        String result = Base64.getEncoder().encodeToString(outputStream.toByteArray());
        log.info("压缩前大小:{}byte, 压缩后大小:{}byte", unzip.getBytes().length, result.getBytes().length);
        return result;
    }

    /**
     * 解压
     *
     * @param zip
     * @return
     */
    @SneakyThrows
    public static String unzipString(String zip) {
        byte[] decode = Base64.getDecoder().decode(zip);
        Inflater inflater = new Inflater();
        inflater.setInput(decode);
        final byte[] bytes = new byte[256];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
        try {
            while (!inflater.finished()) {
                int length = inflater.inflate(bytes);
                outputStream.write(bytes, 0, length);
            }
        } catch (DataFormatException e) {
            e.printStackTrace();
            return null;
        } finally {
            inflater.end();
        }
        return outputStream.toString();

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy