字符串的压缩和解压(包括加解密)


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;
    }
}

你可能感兴趣的:(java,apache,log4j,sun)