Reading a GZIP file from a FileChannel (Java NIO)

2019-02-05 04:12发布

I need to read/unpack a .gz file given a FileChannel.

I've played around with extracting GZIP archives using GZIPInputStream, but this won't take a FileChannel. I don't have access to the original FileInputStream that the FileChannel was taken from.

If someone could tell me a good way (or at least any way) of reading GZIP from a FileChannel, I would greatly appreciate it.

Adapted from a question on the Sun Oracle forums.

2条回答
SAY GOODBYE
2楼-- · 2019-02-05 04:49

You could obtain a wrapping InputStream around the FileChannel:

FileChannel fc = ...
GZIPInputStream gis = new GZIPInputStream(Channels.newInputStream(fc));

Channels is in Java SE.

查看更多
甜甜的少女心
3楼-- · 2019-02-05 05:08

Yes, there is a solution. Implementing GZip is fairly simple. You need a Inflater and CRC32, plus reading the header/trailer. Unfortunately java.util.zip.Inflater takes only byte[] which is suboptimal (a direct Buffer would have been times more efficient). Yet, using non-direct buffer and ByteBuffer.array() is an option.

The built in java.util.zip.CRC32 is quite slow and reimplementing it in java is a nice step towards performance. com.jcraft.jzlib offers pure java implementation (almost looks like pure C, though) and it's possible to replace the byte[] w/ direct Buffer. The library is somewhat slower compared to inflater (decomppress) due to too many bounds check and inability to perform so deep inline. Yet, it's faster on compression.

查看更多
登录 后发表回答