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

rlw182 :

I'm trying to return a list of file names from inside of a tar file. I'm using the code below, but when it gets to the while loop, it immediately goes to the catch exception and says "java.io.IOException: Error detected parsing the header

Below is the code I'm using. Can you help me figure out why this doesn't work?

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;
}
VGR :

Your file is not a tar file. It’s a compressed archive of a tar file.

You cannot open it as a tar file, as is, for the same reason you can’t read a text file while it’s in a zip archive: the bytes representing compressed data are not themselves readable.

The .gz extension of your filename indicates that it was compressed using gzip, which is common when compressing tar files. You can use the GZIPInputStream class to uncompress it:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193564&siteId=1
Recommended