Video in progress
Reading a file written with `GZIPOutputStream` throws `EOFException: Unexpected end of ZLIB input stream`. What could be the cause?
A gzip stream writes a trailer (CRC32 and the original length) at the end, and it only comes out on finish() or close(). If the stream is not closed, or the result is taken before that, the file is left incomplete and the reader decides it is corrupt.
📖 Answer
The most common form is taking the result before closing:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gz = new GZIPOutputStream(bos);
gz.write(json.getBytes(StandardCharsets.UTF_8));
return bos.toByteArray(); // the trailer is not written yet, the last block is inside the deflater
The deflater accumulates data internally. flush() doesn't help here either: by default GZIPOutputStream.flush() does not drain the deflater, it only does so when you use new GZIPOutputStream(out, true) (syncFlush), and even then the trailer is not written.
The correct way:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (GZIPOutputStream gz = new GZIPOutputStream(bos)) {
gz.write(json.getBytes(StandardCharsets.UTF_8));
} // close() -> finish() -> trailer
return bos.toByteArray();
If you need to keep the underlying stream open (for example an HTTP response, or several gzip members in one file), you call gz.finish() instead of close().
A similar trap: if a Writer is wrapped on top of gzip, you have to close the outermost writer. If you only call gz.close(), the last characters in the writer's buffer never reach the gzip. It is easy to check: gzip -t file.gz says "unexpected end of file" on an incomplete file.
Sign up to mark studied questions and save your progress.