2015-03-31 237 views
1

我正在使用FileChannelFileInputStream做一个简单的文件复制从File从文件到File文件。NIO GZIP压缩和复制文件

的代码基本上是这样的:

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(); 

和代码的所有其余保持不变的简单方法。你有没有建议最干净的解决方案?

谢谢..

+0

你使用Java 7+吗? – fge 2015-03-31 10:11:53

+0

是的,我用Java 7+ – bozeng 2015-03-31 10:12:25

+0

[从FileChannel(Java NIO)读一个GZIP文件]中可能重复(http://stackoverflow.com/questions/3335969/reading-a-gzip-file-from-a-filechannel -java-nio) – 2015-03-31 20:42:53

回答

0

你可以换你在FileInputStream一个GZIPInputStream像这样:

InputStream input = new GZIPInputStream(yourCompressedInput);

压缩写作时,你应该使用GZIPOutputStream。

祝你好运。

+0

但是这些包装没有getChannels()正确的 – bozeng 2015-03-31 10:13:45

+1

不,你会使用渠道来获取流。但是再次,这个问题是http://stackoverflow.com/questions/3335969/reading-a-gzip-file-from-a-filechannel-java-nio的重复。你可以在那里找到答案。 – 2015-03-31 20:43:11