在做工程過程中,把做工程過程較好的代碼片段做個收藏奢驯,下邊資料是關(guān)于Java字符串壓縮和解壓縮的代碼申钩,希望能對大家有較大好處。
package com.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class ZipUtil {
? public static String compress(String str) throws IOException {
? ? if (str == null || str.length() == 0) {
? ? ? return str;
? ? }
? ? ByteArrayOutputStream out = new ByteArrayOutputStream();
? ? GZIPOutputStream gzip = new GZIPOutputStream(out);
? ? gzip.write(str.getBytes());
? ? gzip.close();
? ? return out.toString("ISO-8859-1");
? }
? public static String uncompress(String str) 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();
? }
? public static void main(String[] args) throws IOException {
? String str="%5B%7B%22lastUpdateTime%22%3A%222011-10-28+9%3A39%3A41%22%2C%22smsList%22%3A%5B%7B%22liveState%22%3A%221";
? System.out.println("原長度:"+str.length());?
? System.out.println("壓縮后:"+ZipUtil.compress(str).length());?
? ? System.out.println("解壓縮:"+ZipUtil.uncompress(ZipUtil.compress(str)));
? }
}
運行結(jié)果:
原長度:104
壓縮后:95