javainputstreamfileinputstreamfileoutputstreamgunzip

Unexpected end of ZLIB input stream in java


public class GzExtractor implements Extractor {
    Logger logger = LoggerFactory.getLogger(GzExtractor.class);
    private static final int BUFFER_SIZE = 1024;

    byte[] buff = new byte[BUFFER_SIZE];
    private File file;
    private String destinationPath;

    public GzExtractor(File file, String destinationPath) {
        this.file = file;
        this.destinationPath = destinationPath;
    }

    public void extract() {

        try {
            File destDir = new File(destinationPath);
            if (!destDir.exists()) {
                destDir.mkdir();
            }
            GZIPInputStream gZipObj = new GZIPInputStream(new FileInputStream(file));
            String extractedFilename = file.getName().split(".gz")[0];
            OutputStream fosObj = new FileOutputStream(destinationPath + extractedFilename);
            int len;
            while ((len = gZipObj.read(buff)) > 0) {
                fosObj.write(buff, 0, len);
            }
            gZipObj.close();
            fosObj.close();
        } catch (Exception e) {
            logger.info("GZ Exception : {}",e.getMessage());
        }
    }
}

I'm getting the error of unexpected ZLIB stream but the file is extracted successfully. I tried some solutions but none of them solved this. I tried closing the gzip stream before reading as I found that from one of the answers here. But that throws another error of course.

I am confused why I'm getting this and I want to basically eliminate the error statement.

[pool-1-thread-1] INFO service.ExtractorImpl.GzExtractor - GZ Exception : Unexpected end of ZLIB input stream

Solution

  • Okay so probably the compressed file was not in the correct format. I was using an FTP server where I was uploading different kinds of files i.e zip, gzip, CSV, etc. It was in my logic that the decompression would occur on the file according to the compression type of the file. While downloading from my FTP server, I forgot to mention the type of file that must be binary to include zip files.

    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

    So the file which was being decompressed must not be in a correct format. Maybe that is why I was getting this error.

    After setting the file type to this, it worked okay.