2

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)
GPI
  • 9,088
  • 2
  • 31
  • 38
Kaleb Blue
  • 487
  • 1
  • 5
  • 20
  • 1
    Are you sure the input file is valid ? Please note that the `buffer` variable inside the while loop does not exist (you probably meant `b`) – GPI May 29 '20 at 20:10

1 Answers1

3

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"?

FoggyDay
  • 11,962
  • 4
  • 34
  • 48