欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java字符串的GZIP压缩和解压

程序员文章站 2024-03-14 14:16:58
...
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class StringUtil {
    public static String compress(String str,String inEncoding) throws IOException {
        if (str == null || str.length() == 0) {
          return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes(inEncoding));
        gzip.close();
        return out.toString("ISO-8859-1");
        
    }
    
    public static String uncompress(String str,String outEncoding) throws IOException {
        if (str == null || str.length() == 0) {
          return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
        GZIPInputStream 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(outEncoding);
    }
}

其中的编码ISO-8859-1不要进行修改,否则会导致java.util.zip.ZipException: Not in GZIP format异常。