GZIPInputStream/GZIPOutputStream是JDK用来压缩/解压缩的工具。下面是一个压缩字符串的例子:
压缩之后的大小为原来的64%左右。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class MainTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 10000; i++) {
sb.append(word.charAt((int) (Math.random() * 26)));
}
String a = sb.toString();
System.out.println(a.length());
String b = compress(a);
System.out.println(b.length());
String c = unCompress(b);
System.out.println(c.length());
}
/**
* @param str
* @return
*/
public static String compress(String str) {
ByteArrayOutputStream bos = null;
GZIPOutputStream out = null;
try {
bos = new ByteArrayOutputStream();
out = new GZIPOutputStream(bos);
out.write(str.getBytes());
//这里一定要先关闭out流才能返回,不然就会出错。
out.close();
return bos.toString("ISO-8859-1");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static String unCompress(String source) {
if (source == null && "".equals(source)) {
return "";
}
GZIPInputStream in = null;
ByteArrayInputStream bis = null;
ByteArrayOutputStream bos = null;
try {
bis = new ByteArrayInputStream(source.getBytes("ISO-8859-1"));
in = new GZIPInputStream(bis);
bos = new ByteArrayOutputStream();
byte[] buf = new byte[256];
int len = 0;
while ((len = in.read(buf)) >= 0) {
bos.write(buf, 0, len);
}
return bos.toString();
} catch (Exception e) {
e.printStackTrace();
} finally
{
try {
in.close();
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}