1. 程式人生 > >Java字串的GZIP壓縮和解壓

Java字串的GZIP壓縮和解壓

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異常。