Search code examples
javaiogzipnio

Writing GZIP file with nio


This is my code:

WritableByteChannel channel = null;
GZIPOutputStream out = null;
try {
     channel = Channels.newChannel(new FileOutputStream("C:\\temp\\111.zip"));

     out = new GZIPOutputStream(Channels.newOutputStream(channel));
    for (long i = 0; i < 10000000000; i++) {    
       out.write(("string" + i + "\n").getBytes());
     } 

   } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (channel != null) {
                channel.close();
            }
        } catch (Exception e) {
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
    }    }

I get zip but it's contents is damaged.


Solution

  • Why are you saving it as zip if you're using a gzip stream? Use .gz as the extension.

    Edit
    Assuming that it's not the .zip extension at fault here (it's still bad though):

    1. You should probably consider calling out.finish() before closing it.
    2. I'm pretty sure you don't need all the channel stuff. You can simply pass the FileOutputStream to GZIPOutputStream