java对字符串进⾏压缩转换复原
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* 字符串压缩
*/
public class ZipStrUtil {
/**
* 恢复字符串
* @param compressedStr
* @return
*/
public static String gunzip(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 = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
in=new ByteArrayInputStream(compressed);
ginzip=new GZIPInputStream(in);java stream
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ad(buffer)) != -1) {
out.write(buffer, 0, offset);
}
String();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return decompressed;
}
/**
* 压缩字符串
* @param primStr
* @return
*/
public static String gzip(String primStr) {
if (primStr == null || primStr.length() == 0) {
return primStr;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip=null;
try {
gzip = new GZIPOutputStream(out);
gzip.Bytes());
} catch (IOException e) {
e.printStackTrace();
}finally{
if(gzip!=null){
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new sun.misc.BASE64Encoder().ByteArray()); }
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论