用nio编写GZIP文件 [英] Writing GZIP file with nio

查看:191
本文介绍了用nio编写GZIP文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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.

推荐答案

如果你使用的是gzip流,为什么要将它保存为zip?使用 .gz 作为扩展名。

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

修改

假设这里不是.zip扩展错误(虽然它仍然很糟糕):

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


  1. 您应该考虑调用 out.finish()关闭之前。

  2. 我很确定你不需要所有的频道资料。您只需将FileOutputStream传递给GZIPOutputStream

  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

这篇关于用nio编写GZIP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆