字符串的压缩和解压

import com.util.IArchive;
import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.log4j.Category;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class CompressImp implements IArchive
{

    private static Category log4j = Category.getInstance("Commonlog");

    private Category        logError;

    public CompressImp()
    {
        logError = Category.getInstance("CommonlogError");
    }

    public String compress(String sourceData)
    {
        String msg;
        msg = "ERROR";
        ByteArrayOutputStream baOS = null;
        GZIPOutputStream zipOS = null;
        try
        {
            baOS = new ByteArrayOutputStream();
            zipOS = new GZIPOutputStream(baOS);
            byte msgBt[] = sourceData.getBytes("UTF-8");
            zipOS.write(msgBt);
            zipOS.close();
            byte zipBt[] = baOS.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            msg = encoder.encode(zipBt);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logError.error("压缩异常" + e.getMessage());
        }
        finally
        {
            try
            {
                baOS.close();
                zipOS.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        return msg;
    }

    public String decompress(String sourceData)
    {
        String dest;
        byte msgBt[] = new byte[51200];
        dest = "ERROR";
        ByteArrayInputStream baIS = null;
        GZIPInputStream zipIS = null;
        BufferedInputStream bIS = null;
        try
        {
            BASE64Decoder decoder = new BASE64Decoder();
            byte zipBt[] = decoder.decodeBuffer(sourceData);
            baIS = new ByteArrayInputStream(zipBt);
            zipIS = new GZIPInputStream(baIS);
            bIS = new BufferedInputStream(zipIS);
            bIS.read(msgBt);
            dest = new String(msgBt, "UTF-8");
            dest = dest.trim();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logError.error("压缩异常" + e.getMessage());
        }
        finally
        {
            try
            {
                baIS.close();
                zipIS.close();
                bIS.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        return dest;
    }
}
 
作者日志分类 [全部日志 ]
[休闲搞笑 ] [全部分类 ]

<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值