Exception: Unexpected end of ZLIB input stream

后端 未结 1 741
南方客
南方客 2020-11-29 05:37

There is something wrong with GZIPInputStream or GZIPOutputStream. Just please read the following code (or run it and see what happens):

         


        
相关标签:
1条回答
  • 2020-11-29 05:46

    You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

    Here's 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();       // Remove this to reproduce the reported bug
            System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
        }
    }
    

    (I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

    0 讨论(0)
提交回复
热议问题