字符串压缩解压

package test.compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;


public class StringCompress {

	// 压缩
	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 decompress(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("GBK");
	}

	public static void test() throws IOException {
		String str1 = "";
		for (int i = 0; i < 100; i++) {
			str1 += "<word>goodjob中文</word>";
		}
		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
		
		// 压缩前进行BASE64
		String base64data1 = encoder.encodeBuffer(str1.getBytes());
		System.out.println(base64data1.length());
		try {
			String compressed = compress(str1);
			// 压缩后进行BASE64
			String base64data2 = encoder.encodeBuffer(compressed.getBytes("ISO-8859-1"));
			System.out.println(base64data2.length());
			
			String str2 = decompress(new String(decoder.decodeBuffer(base64data2),"ISO-8859-1"));
			System.out.println(str2.equals(str1));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		try {
			test();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
 

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