通过java原生API将字符串进行压缩和解压缩,参考使用了别人的代码后,报异常了(Unexpected end of ZLIB input stream)。
在解压缩函数的gunzip.read(buffer)出了问题,跟踪进去看,异常由InflaterInputStream类的fill函数抛出。
protected void fill() throws IOException {
ensureOpen();
len = in.read(buf, 0, buf.length);
if (len == -1) {
throw new EOFException("Unexpected end of ZLIB input stream");
}
inf.setInput(buf, 0, len);
}
public static String GetCompress(String src)
{
if (src == null || src.isEmpty()) {
return src;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
String des = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(src.getBytes());
//由于压缩后的数据需要传输,所以用了BASE64编码
des = new BASE64Encoder().encode(out.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}finally{
if(gzip!=null)
{
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return des;
}
public static String GetDeCompress(String src)
{
if (src == null || src.isEmpty()) {
return src;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gunzip = null;
String des = null;
try {
ByteArrayInputStream in = new ByteArrayInputStream(
new BASE64Decoder().decodeBuffer(src));
gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int n;