java对gzip格式进行压缩与解压缩

java对gzip格式进行压缩和解压缩

对gzip格式字符串进行解压缩
public static String unzip(String compressedStr){
if(compressedStr ==null){
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
GZIPInputStream ginzip = null;
byte[] compressed = null;
String decompressed = null;
try{
compressed = compressedStr.getBytes(“ISO-8859-1”);
in = new ByteArrayInputStream(compressed);
ginzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset = -1;
while((offset = ginzip.read(buffer)) != -1){
out.write(buffer,0,offset);
}
out.flush();
decompressed = out.toString();
if(ginzip != null)
ginzip.close;
if(in != null)
in.close();
if(out != null)
out.close();
}catch(IOException e){
e.printStackTrace();
}
return decompressed;
}


使用gzip进行压缩
public static String gzip(String primStr) throws UnsupporttEncodingException{
if(primStr == null || primStr.length() == 0)
return primStr;
ByteArrayOutputStream out = new ByteAttayOutputStream();
GZIPOutputStream gzip = null;
try{
gzip = new GZIPOutputStream(out);
gzip.write(primStr.getBytes());
gzip.close();
}catch(IOException e){
e.printStackTrace();
}
return out.toString(“ISO-8859-1”);
}

猜你喜欢

转载自blog.csdn.net/qq_37225699/article/details/81666521