2015-03-31 121 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