1

I was using FileChannel and FileInputStream to do a simple file copying from File fromFile to File toFile.

The code is basically like this:

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

where fromFile and toFile are proper File objects. Now, instead of copying from fromFile directly, i wanted to compress its content using GZIP (found in Java libraries) and then copy to toFile. Also reversely, when I transfer back from toFile, I would like to decompress it as well.

I was wondering is there a simple way like

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

or

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

and all the rest of code remain unchanged. Do you have any suggestion on the cleanest solution to this?

Thanks..

bozeng
  • 245
  • 1
  • 2
  • 10
  • possible duplicate of [Reading a GZIP file from a FileChannel (Java NIO)](http://stackoverflow.com/questions/3335969/reading-a-gzip-file-from-a-filechannel-java-nio) – Bert Peters Mar 31 '15 at 20:42

1 Answers1

0

You could wrap your FileInputStream in a GZIPInputStream like so:

InputStream input = new GZIPInputStream(yourCompressedInput);

For compressing when writing, you should use the GZIPOutputStream.

Good luck.

Bert Peters
  • 1,505
  • 13
  • 30
  • 1
    No, you would use the channels to get a stream. But then again, this question is a duplicate of http://stackoverflow.com/questions/3335969/reading-a-gzip-file-from-a-filechannel-java-nio. You can find the answer there. – Bert Peters Mar 31 '15 at 20:43