我正在尝试从tar文件内部返回文件名列表。我正在使用下面的代码,但是当它进入while循环时,它立即转到catch异常并显示“ java.io.IOException:检测到解析标头时出错
下面是我正在使用的代码。您能帮我弄清楚为什么这行不通吗?
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;
}
答案 0 :(得分:0)
您的文件不是tar文件。这是tar文件的压缩存档。
您不能按原样将其打开为tar文件,出于同样的原因,您无法在zip存档中读取文本文件:表示压缩数据的字节本身不可读。
文件名的.gz
扩展名表明它是使用gzip压缩的,这在压缩tar文件时很常见。您可以使用GZIPInputStream类对其进行解压缩:
TarArchiveInputStream tarInput = new TarArchiveInputStream(
new GZIPInputStream(
new BufferedInputStream(
new FileInputStream(filePath))));