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();
gzip.finish();
// return out.toString("ISO-8859-1");
return out.toString("UTF-8");
}
// 解压缩
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("utf-8"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer))>=0) {
out.write(buffer, 0, n);
}
// toString()使用平台默认编码,也可以显式的指定如toString("GBK")
return out.toString();
}
Exception in thread "main" java.io.IOException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:141)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:56)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:65)
at Util.ZipUtil2.uncompress(ZipUtil2.java:106)
at Util.ZipUtil2.main(ZipUtil2.java:126)
public static byte[] compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return null;
}
byte[] outPut = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
gzip.finish();
outPut = out.toByteArray();
// return out.toString("ISO-8859-1");
return outPut;
}
// 解压缩
public static String uncompress(byte[] str) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(str);
GZIPInputStream gunzip = new GZIPInputStream(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
// toString()使用平台默认编码,也可以显式的指定如toString("GBK")
return out.toString();
}
public static void main(String[] args) {
try {
byte[] b=Test.compress("111111111111");
System.out.println(Test.uncompress(b));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
改成上面的就好了,已测