GZIP compression to a byte array

后端 未结 6 1160
星月不相逢
星月不相逢 2020-12-13 21:00

I am trying to write a class that can compress data. The below code fails (no exception is thrown, but the target .gz file is empty.)
Besides: I don\'t want to generate

6条回答
  •  不知归路
    2020-12-13 21:24

    The problem is that you are not closing the GZIPOutputStream. Until you close it the output will be incomplete.

    You just need to close it before reading the byte array. You need to reorder the finally blocks to achieve this.

    import java.io.*;
    import java.util.zip.*;
    import java.nio.charset.*;
    
    public class Zipper
    {
      public static void main(String[] args)
      {    
        byte[] dataToCompress = "This is the test data."
          .getBytes(StandardCharsets.ISO_8859_1);
    
        try
        {
          ByteArrayOutputStream byteStream =
            new ByteArrayOutputStream(dataToCompress.length);
          try
          {
            GZIPOutputStream zipStream =
              new GZIPOutputStream(byteStream);
            try
            {
              zipStream.write(dataToCompress);
            }
            finally
            {
              zipStream.close();
            }
          }
          finally
          {
            byteStream.close();
          }
    
          byte[] compressedData = byteStream.toByteArray();
    
          FileOutputStream fileStream =
            new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
          try
          {
            fileStream.write(compressedData);
          }
          finally
          {
            try{ fileStream.close(); }
              catch(Exception e){ /* We should probably delete the file now? */ }
          }
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
      }
    }
    

    I do not recommend inititalizing the stream variables to null, because it means your finally block can also throw a NullPointerException.

    Also note that you can declare main to throw IOException (then you would not need the outermost try statement.)

    There is little point in swallowing exceptions from zipStream.close();, because if it throws an exception you will not have a valid .gz file (so you should not proceed to write it.)

    Also I would not swallow exceptions from byteStream.close(); but for a different reason - they should never be thrown (i.e. there is a bug in your JRE and you would want to know about that.)

提交回复
热议问题