java字符串压缩工具类

package com.hcyt.common.sqnUtils;
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.commons.io.IOUtils;

/**
 * @author jack.liang
 *
 */
public class ZipBlobContentUtil {

	   public static String compressToByte(String str,String encoding){
	        if (str == null || str.length() == 0) { 
	            return null; 
	        }
	        ByteArrayOutputStream out = new ByteArrayOutputStream();
	        GZIPOutputStream gzip = null;
	        try { 
	            gzip = new GZIPOutputStream(out); 
	            gzip.write(str.getBytes(encoding)); 
	        } catch (IOException e) { 
	            e.printStackTrace();
	        }finally{
	        	  IOUtils.closeQuietly(gzip);
	        } 
	        return out.toByteArray().toString();
	    } 
	  
	    
	    
	   /*     * 字节数组解压缩后返回字符串     */ 
	    public static String uncompressToString(byte[] b, String encoding) { 
	       if (b == null || b.length == 0) { 
	            return null; 
	        }
	        ByteArrayOutputStream out = new ByteArrayOutputStream();
	        ByteArrayInputStream in = new ByteArrayInputStream(b);
	        GZIPInputStream gunzip =null ; 
	        try {
	            gunzip = new GZIPInputStream(in);
	            byte[] buffer = new byte[256];
	            int n; 
	            while ((n = gunzip.read(buffer)) >= 0) { 
	               out.write(buffer, 0, n);
	            }
	            return out.toString(encoding);
	        } catch (IOException e) { 
	            e.printStackTrace(); 
	        }finally{
	        	IOUtils.closeQuietly(in);
	        	IOUtils.closeQuietly(out);
				IOUtils.closeQuietly(gunzip);
	        } 
	        return null;
	    }
}

 

你可能感兴趣的:(java)