日期:2014-05-20  浏览次数:23238 次

java解压缩出现异常:Unexpected end of ZLIB input stream
本帖最后由 vaintwyt 于 2014-04-18 12:13:14 编辑
    想通过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);
    }


    百度和google了一轮,都没有找到解决方法。。。请求大神出手啊!

    代码如下:



        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;
n = gunzip.read(buffer);
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
des = out.toString();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(gunzip!=null)
{
try {
gunzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return des;
}

------解决方案--------------------
压缩用Deflater类。