GZIPInputStream 适用于 FileInputStream 但不适用于 InputStream

GZIPInputStream works with FileInputStream but not InputStream

我在使用 GZIPInputStream 时注意到,在 gzip 文件上使用从 Class.class.getResourceAsStream 生成的 InputStream 会导致

java.util.zip.ZipException: invalid code lengths set

在 GZIPInputStream 中使用时,但在同一文件上使用 FileInputStream 似乎工作正常。有谁知道是什么原因造成的?

例如:

InputStream is = new FileInputStream("src/main/resources/testFile.gz");
GZIPInputStream zis = new GZIPInputStream(is);
String outputStr = IOUtils.toString(zis, "utf-8");

成功生成带有解压文件数据的输出字符串,同时:

InputStream is = Class.class.getResourceAsStream("/testFile.gz");
GZIPInputStream zis = new GZIPInputStream(is);
String outputStr = IOUtils.toString(zis, "utf-8");

生成上面的 ZipException。

当我解压缩文件时,我能够使用 IOUtils.toString 在以任何方式生成的 InputStream 上获得正确的输出字符串,所以我知道文件正在被成功访问并且问题似乎与GZIPInputStream 本身。

事实证明,Maven 是导致使用 getResourceAsStream 生成 ZipException 而 FileInputStream 却没有的罪魁祸首。我在 src/main/resources 下的 gz 文件被 Maven 复制到 target/src/main/resources,随后在应用 Maven 过滤时自动损坏。 FileInputStream 以 src/main/resources 下的文件为目标,而 getResourceAsStream 以 target/src/main/resources 下的文件为目标。该问题的解决方案是禁用对 src/main/resources 目录中我的资源的过滤,如下所示。

<resource>
  <directory>src/main/resources</directory>
  <includes>
    <include>**/*</include>
  </includes>
  <filtering>false</filtering>
</resource>