从 FileChannel 读取 GZIP 文件 (Java NIO)

发布于 2024-09-11 19:31:14 字数 362 浏览 1 评论 0原文

我需要读取/解压给定 FileChannel 的 .gz 文件。

我尝试过使用 GZIPInputStream 提取 GZIP 档案,但这不需要 FileChannel。我无权访问从中获取 FileChannel 的原始 FileInputStream。

如果有人能告诉我一种从 FileChannel 读取 GZIP 的好方法(或至少任何方式),我将不胜感激。

改编自 Sun Oracle 论坛上的问题.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽你眉间 2024-09-18 19:31:14

您可以获得围绕 FileChannel 的包装 InputStream:

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

Channels 位于 Java SE 中。

You could obtain a wrapping InputStream around the FileChannel:

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

Channels is in Java SE.

丢了幸福的猪 2024-09-18 19:31:14

是的,有一个解决方案。实现 GZip 相当简单。您需要充气机和 CRC32,以及阅读标题/预告片。不幸的是,java.util.zip.Inflater只需要byte[],这是次优的(直接Buffer的效率会高很多倍)。然而,使用非直接缓冲区和 ByteBuffer.array() 是一种选择。

内置的 java.util.zip.CRC32 非常慢并且需要重新实现java 中的它是向性能迈出的一个很好的一步。 com.jcraft.jzlib 提供纯java实现(不过看起来几乎像纯C),它是可以用直接缓冲区替换 byte[]。由于边界检查太多并且无法执行如此深度的内联,该库与 inflate(解压缩)相比要慢一些。然而,它的压缩速度更快。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文