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 main(String[] args) throws IOException
{
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
String msg = "";
System.out.println("压缩前长度:" + msg.length());
//压缩
String c = compress(msg);
// 压缩后进行BASE64
String base64data2 = encoder.encodeBuffer(c.getBytes("ISO-8859-1"));
System.out.println("压缩后长度:" + base64data2.length());
//解压前进行反BASE64
byte[] b = decoder.decodeBuffer(base64data2);
//解压
String d = decompress(new String(b, "ISO-8859-1"));
System.out.println("解压后长度:" + d.length());
}
}
压缩字符
最新推荐文章于 2022-09-26 23:36:53 发布