java - 使用nio写入GZIP文件

标签 java io gzip nio

这是我的代码:

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) {
        }
    }    }

我得到了 zip,但它的内容已损坏。

最佳答案

我会这样做:

GZIPOutputStream gzipOS = new GZIPOutputStream(new FileOutputStream("C:\\temp\\111.gz"));
WritableByteChannel out = Channels.newChannel(gzipOS);

并且只需使用out.write()即可使用NIO进行写入。不要忘记稍后关闭资源。

关于java - 使用nio写入GZIP文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9394098/

相关文章:

java - 架构 "DB"不存在

java - 可选<长> 到可选<即时>

java - 为什么 getClass().getResource 对 RandomAccessFile/ReversedLinesFileReader (Apache Commons) 有问题?

java - 套接字镜像发送但不接收

javascript - Pako 无法压缩 python 中生成的 gzip 文件

java - 处理参数作为类型

java - JNI 'problematic frame' 导致 JVM 崩溃

java - 在资源文件夹下的 JUnit 测试中写入一个文件

android - 为什么 Android aapt 去掉 assets 的 .gz 文件扩展名?

c++ - 使用zlib1.2.7解压gzip数据,如何获取压缩包中的文件名