字符串解压缩

package com.csf.myproduct.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;


import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * <strong style="background-color: rgb(204, 102, 0);">return new BASE64Encoder().encode(out.toByteArray());需要放在out对象关闭之后,不然解压时会报错。</strong>
 *
 * 对字符串进行加解密和加解压
 * Createy by user on 9/11/2018.16:38
 */
public class Base64Gzip {

    private static final String CHARSET = "gbk";

    private static Logger log = Logger.getLogger(Base64Gzip.class);


    public static void main(String[] args) throws IOException {
        // 字符串超过一定的长度
        String str = "ABCdef123中文~!@#$%^&*()_+{};/1111111111111111111111111AAAAAAAAAAAJDLFJDLFJDLFJLDFFFFJEIIIIIIIIIIFJJJJJJJJJJJJALLLLLLLLLLLLLLLLLLLLLL" +
                "LLppppppppppppppppppppppppppppppppppppppppp===========================------------------------------iiiiiiiiiiiiiiiiiiiiiii";
        System.out.println("\n原始的字符串为------->" + str);
        float len0 = str.length();
        System.out.println("原始的字符串长度为------->" + len0);

        String ys = gzipString(str);
        System.out.println("\n压缩后的字符串为----->" + ys);
        float len1 = ys.length();
        System.out.println("压缩后的字符串长度为----->" + len1);

        String jy = ungzipString(ys);
        System.out.println("\n解压缩后的字符串为--->" + jy);
        System.out.println("解压缩后的字符串长度为--->" + jy.length());

        System.out.println("\n压缩比例为" + len1 / len0);

        //判断
        if (str.equals(jy)) {
            System.out.println("先压缩再解压以后字符串和原来的是一模一样的");
        }
    }


    /**
     * 将字符串压缩后Base64
     *
     * @param primStr 待加压加密函数
     * @return
     */
    public static String gzipString(String primStr) {
        if (primStr == null || primStr.length() == 0) {
            return primStr;
        }
        ByteArrayOutputStream out = null;
        GZIPOutputStream gout = null;
        try {
            out = new ByteArrayOutputStream();
            gout = new GZIPOutputStream(out);
            gout.write(primStr.getBytes(CHARSET));
            gout.flush();
        } catch (IOException e) {
            log.error("对字符串进行加压加密操作失败:", e);
            return null;
        } finally {
            if (gout != null) {
                try {
                    gout.close();
                } catch (IOException e) {
                    log.error("对字符串进行加压加密操作,关闭gzip操作流失败:", e);
                }
            }
        }
        return new BASE64Encoder().encode(out.toByteArray());
    }

    /**
     * 将压缩并Base64后的字符串进行解密解压
     *
     * @param compressedStr 待解密解压字符串
     * @return
     */
    public static final String ungzipString(String compressedStr) {
        if (compressedStr == null) {
            return null;
        }
        ByteArrayOutputStream out = null;
        ByteArrayInputStream in = null;
        GZIPInputStream gin = null;
        String decompressed = null;
        try {
            byte[] compressed = new BASE64Decoder().decodeBuffer(compressedStr);
            out = new ByteArrayOutputStream();
            in = new ByteArrayInputStream(compressed);
            gin = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = gin.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = out.toString(CHARSET);
        } catch (IOException e) {
            log.error("对字符串进行解密解压操作失败:", e);
            decompressed = null;
        } finally {
            if (gin != null) {
                try {
                    gin.close();
                } catch (IOException e) {
                    log.error("对字符串进行解密解压操作,关闭压缩流失败:", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("对字符串进行解密解压操作,关闭输入流失败:", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("对字符串进行解密解压操作,关闭输出流失败:", e);
                }
            }
        }
        return decompressed;
    }

}



==================================================
package com.csf.myproduct.common;

import com.csf.myproduct.core.nio.demo1.MyServer3;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * <strong style="background-color: rgb(204, 102, 0);">return new BASE64Encoder().encode(out.toByteArray());需要放在out对象关闭之后,不然解压时会报错。</strong>
 * <p>
 * Createy by user on 9/11/2018.16:10
 */
public class Base64Zip {

    private static final String CHARSET = "gbk";

    private final static Logger log = Logger.getLogger(MyServer3.class.getName());

    public static void main(String[] args) throws IOException {
        // 字符串超过一定的长度
        String str = new String("{\"ProductCode\": \"q\",\"HighestPrice\": \"w\",\"LowestPrice\": \"e\",\"OpeningPrice\": \"r\",\"LatestPrice\": \"123456789\",\"PriceChangePoint\":\"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中>中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中0\",\"PriceChangeRatio\":\"0.0000\",\"ValueDate\":1535009734533,\"MarketDataUpdatedTime\": 1509706096000,\"TradeVolumeFlag\": \"0\",\"DateConfirmed\": 1509638400000,\"TakerDirection\":\"S\",\"CurrencyPairCode\": \"USD/CNY\",\"CfetsUnifiedCode\": \"CNY=CFHC\",\"DealMarketDateType\": \"2\",\"TradingMode\": \"9\"}");
        System.out.println("\n原始的字符串为------->" + str);
        float len0 = str.length();
        System.out.println("原始的字符串长度为------->" + len0);

        String ys = zipString(str);
        System.out.println("\n压缩后的字符串为----->" + ys);
        float len1 = ys.length();
        System.out.println("压缩后的字符串长度为----->" + len1);

        String jy = unzipString(ys);
        System.out.println("\n解压缩后的字符串为--->" + jy);
        System.out.println("解压缩后的字符串长度为--->" + jy.length());

        System.out.println("\n压缩比例为" + len1 / len0);

        //判断
        if (str.equals(jy)) {
            System.out.println("先压缩再解压以后字符串和原来的是一模一样的");
        }
    }


    /**
     * 将字符串压缩后Base64
     * @return
     */
    public static String zipString(String primStr) {
        if (primStr == null || primStr.length() == 0) {
            return primStr;
        }
        ByteArrayOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = new ByteArrayOutputStream();
            zout = new ZipOutputStream(out);
            zout.putNextEntry(new ZipEntry("0"));
            zout.write(primStr.getBytes(Charset.forName(CHARSET)));
            zout.closeEntry();
            return new BASE64Encoder().encode(out.toByteArray());
        } catch (IOException e) {
            log.error("对字符串进行加压加密操作失败:", e);
            return null;
        } finally {
            if (zout != null) {
                try {
                    zout.close();
                } catch (IOException e) {
                    log.error("对字符串进行加压加密操作,关闭zip操作流失败:", e);
                }
            }
        }
    }


    /**
     * 将压缩并Base64后的字符串进行解密解压
     * @return
     */
    public static final String unzipString(String compressedStr) {
        if (compressedStr == null) {
            return null;
        }
        ByteArrayOutputStream out = null;
        ByteArrayInputStream in = null;
        ZipInputStream zin = null;
        String decompressed = null;
        try {
            byte[] compressed = new BASE64Decoder().decodeBuffer(compressedStr);
            out = new ByteArrayOutputStream();
            in = new ByteArrayInputStream(compressed);
            zin = new ZipInputStream(in);
            zin.getNextEntry();
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = zin.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = out.toString(CHARSET);
        } catch (IOException e) {
            log.error("对字符串进行解密解压操作失败:", e);
            decompressed = null;
        } finally {
            if (zin != null) {
                try {
                    zin.close();
                } catch (IOException e) {
                    log.error("对字符串进行解密解压操作,关闭压缩流失败:", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("对字符串进行解密解压操作,关闭输入流失败:", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("对字符串进行解密解压操作,关闭输出流失败:", e);
                }
            }
        }
        return decompressed;
    }


}


==================================================

package com.csf.myproduct.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 对字符串的压缩及解压 GZIP 方式
 * Createy by user on 9/11/2018.15:44
 */
public class GzipStrUtil {

    private static final String CHARSET = "ISO-8859-1";

    public static void main(String[] args) throws IOException {
        // 字符串超过一定的长度
        String str = "ABCdef123中文~!@#$%^&*()_+{};/1111111111111111111111111AAAAAAAAAAAJDLFJDLFJDLFJLDFFFFJEIIIIIIIIIIFJJJJJJJJJJJJALLLLLLLLLLLLLLLLLLLLLL" +
                "LLppppppppppppppppppppppppppppppppppppppppp===========================------------------------------iiiiiiiiiiiiiiiiiiiiiii";
        System.out.println("\n原始的字符串为------->" + str);
        float len0 = str.length();
        System.out.println("原始的字符串长度为------->" + len0);

        String ys = compressGzip(str);
        System.out.println("\n压缩后的字符串为----->" + ys);
        float len1 = ys.length();
        System.out.println("压缩后的字符串长度为----->" + len1);

        String jy = unCompressGzip(ys);
        System.out.println("\n解压缩后的字符串为--->" + jy);
        System.out.println("解压缩后的字符串长度为--->" + jy.length());

        System.out.println("\n压缩比例为" + len1 / len0);

        //判断
        if (str.equals(jy)) {
            System.out.println("先压缩再解压以后字符串和原来的是一模一样的");
        }
    }

    /**
     * 字符串的压缩
     *
     * @param str 待压缩的字符串
     * @return 返回压缩后的字符串
     * @throws IOException
     */
    public static String compressGzip(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的 byte 数组输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 使用默认缓冲区大小创建新的输出流
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        // 将 b.length 个字节写入此输出流
        gzip.write(str.getBytes());
        gzip.close();
        // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
        return out.toString(CHARSET);
    }

    /**
     * 字符串的解压
     *
     * @param str 对字符串解压
     * @return 返回解压缩后的字符串
     * @throws IOException
     */
    public static String unCompressGzip(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的 byte 数组输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(CHARSET));
        // 使用默认缓冲区大小创建新的输入流
        GZIPInputStream gzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n = 0;
        while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组
            // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
            out.write(buffer, 0, n);
        }
        // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
//        return out.toString("GBK");
        return out.toString();
    }

}

猜你喜欢

转载自www.cnblogs.com/xiaolei2017/p/9629339.html