Kaleb Blue
Kaleb Blue

Reputation: 507

How to fix EOF read error with GZIPInputStream

I am trying to read the contents of a gzip file and create a file from it. I'm running into an issue that I can't see to figure out. Any ideas of suggestion is appreciated. Thank you.

private static String unzip(String gzipFile, String location){

        try {
            FileInputStream in = new FileInputStream(gzipFile);
            FileOutputStream out = new FileOutputStream(location);
            GZIPInputStream gzip = new GZIPInputStream(in);

            byte[] b = new byte[1024];
            int len;
            while((len = gzip.read(b)) != -1){
                out.write(buffer, 0, len);
            }

            out.close();
            in.close();
            gzip.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:116)
at java.io.FilterInputStream.read(FilterInputStream.java:107)

Upvotes: 2

Views: 1601

Answers (1)

paulsm4
paulsm4

Reputation: 121849

You'll make life much easier on yourself by using Resource Blocks to ensure your files are closed correctly. For example:

private static String unzip(String gzipFile, String location){

        try (
            FileInputStream in = new FileInputStream(gzipFile);
            GZIPInputStream gzip = new GZIPInputStream(in);
            FileOutputStream out = new FileOutputStream(location))
        {

            byte[] b = new byte[4096];
            int len;
            while((len = gzip.read(b)) >= 0){
                out.write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

You should also ensure you've got a valid .zip file (of course!) and that your input and output filenames are different.

And what's going on with "buffer"? I assume (as does GPI) you probably meant "b"?

Upvotes: 2

Related Questions