通过gzip对字符串压缩

通过GZIPOutputStream,GZIPInputStream可以方便的对数据进行压缩,本以为很简单的代码,写好运行居然报错:

 

Exception in thread "main" java.io.EOFException: Unexpected end of ZLIB input stream
    at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:223)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:141)
    at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:92)
    at java.io.FilterInputStream.read(FilterInputStream.java:90)
    at Main.main(Main.java:25)

 

代码很简单:

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write("testlalala2389223423sdfds383274llalall".getBytes());
        byte[] data = out.toByteArray();
        GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(data));
        data = new byte[gunzip.available()];
        gunzip.read(data);

 

打点分析:

 System.out.println("data_length "+data.length);

 System.out.println("data_available "+gunzip.available());

data_length 10
data_available 1

 

原因:

1.没有 gzip.close();

2. gunzip.available()不能获取正确的数据,改成while

 

完整的代码:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Main {

    public static void main(String[] args) throws Exception {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write("testlalala23892234分詞誒四是23sdfds383274llalall".getBytes("utf-8"));
        gzip.close();

        byte[] data = out.toByteArray();
        System.out.println("data_length " + data.length);

        GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(data));
        System.out.println("data_available " + gunzip.available());

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            outStream.write(buffer, 0, n);
        }
        System.out.println(outStream.toString("utf-8"));
    }
}
 

你可能感兴趣的:(GZip)