Java – exception: zlib input stream ended unexpectedly
There is a problem with gzipinputstream or gzipoutputstream Read the following code (or run it to see what happens):
def main(a: Array[String]) { val name = "test.dat" new GZIPOutputStream(new FileOutputStream(name)).write(10) println(new GZIPInputStream(new FileInputStream(name)).read()) }
It creates a file test DAT, write a single byte 10 format by gzip, and read the bytes in the same file in the same format
This is how I run it:
Exception in thread "main" java.io.EOFException: Unexpected end of ZLIB input stream at java.util.zip.InflaterInputStream.fill(UnkNown Source) at java.util.zip.InflaterInputStream.read(UnkNown Source) at java.util.zip.GZIPInputStream.read(UnkNown Source) at java.util.zip.InflaterInputStream.read(UnkNown Source) at nbt.Test$.main(Test.scala:13) at nbt.Test.main(Test.scala)
For some reason, the reading line seems to be wrong
I accidentally ended Google's wrong zlib input stream and found some error reports about Oracle released from 2007 to 2010 So I guess this error is still to some extent, but I don't know whether my code is correct, so let me post here and listen to your opinion thank you!
Solution
You must call close () before GZIPOutputStream, and then try to read it. The final byte of the file will be written only when the file is actually closed (this has nothing to do with any explicit buffer in the output stack. Only when you tell it to close, the stream can only compress and write the last byte. Flush () may not help... Although calling finish () instead of close () should work. See JavaDocs.)
This is the correct code (in Java);
package test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GZipTest { public static void main(String[] args) throws FileNotFoundException,IOException { String name = "/tmp/test"; GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name)); gz.write(10); gz.close(); System.out.println(new GZIPInputStream(new FileInputStream(name)).read()); } }
(I don't implement resource management correctly. Don't think of it as an example of "good code".)