无法获取 Java 中的 .tar 文件中的文件列表

Not able to get the list of file in a .tar file in Java

我正在尝试从 tar 文件中 return 文件名列表。我正在使用下面的代码,但是当它进入 while 循环时,它会立即转到 catch 异常并显示“java.io.IOException:检测到解析 header

时出错

下面是我正在使用的代码。你能帮我弄清楚为什么这不起作用吗?

public List<String> getFilesInTar(String filename) {
  List<String> foundFiles = Lists.newArrayList();
  String filePath = System.getProperty("user.home") + File.separator + "Downloads" + File.separator + filename;
  try {
      TarArchiveInputStream tarInput = new TarArchiveInputStream(new FileInputStream(filePath));
      TarArchiveEntry entry;
      while ((entry = tarInput.getNextTarEntry()) != null) {
          if (!entry.isDirectory()) {
              foundFiles.add(entry.getName());
          }
      }
      tarInput.close();
  } catch (IOException ex) {
      log.error(ex.getMessage());
  }
  return foundFiles;
}

您的文件不是 tar 文件。它是 tar 文件的压缩存档。

您不能将它作为 tar 文件打开,因为同样的原因,当它在 zip 存档中时您不能读取文本文件:表示压缩数据的字节本身不可读。

文件名的 .gz 扩展名表明它是使用 gzip 压缩的,这在压缩 tar 文件时很常见。您可以使用 GZIPInputStream class 来解压缩它:

  TarArchiveInputStream tarInput = new TarArchiveInputStream(
        new GZIPInputStream(
            new BufferedInputStream(
                new FileInputStream(filePath))));