NIO GZIP压缩和复制文件

时间:2015-03-31 10:03:22

标签: java filechannel gzipinputstream gzipoutputstream

我使用FileChannelFileInputStream进行从File从文件到File到文件的简单文件复制。

代码基本上是这样的:

source = new FileInputStream(fromFile).getChannel();
destination = new FileOutputStream(toFile, false).getChannel(); // overwrite
destination.transferFrom(source, 0, source.size());

其中fromFiletoFile是正确的File个对象。 现在,我不想直接从fromFile复制,而是想使用GZIP(在Java库中找到)压缩其内容,然后复制到toFile。另外,当我从toFile转回时,我也希望将其解压缩。

我想知道有一种简单的方法,比如

source = new GZIPCompressInputStream(new FileInputStream(fromFile)).getChannel();

source = new GZIPDecompressInputStream(new FileInputStream(fromFile)).getChannel();

并且所有其余代码保持不变。你对这个最干净的解决方案有什么建议吗?

谢谢..

1 个答案:

答案 0 :(得分:0)

您可以将FileInputStream包裹在GZIPInputStream中,如此:

InputStream input = new GZIPInputStream(yourCompressedInput);

对于写入时的压缩,您应该使用GZIPOutputStream。

祝你好运。