10

Ok so I want to read the contents of a tar.gz file (or a xy) but that's the same thing. What I am doing is more or less this:

TarArchiveInputStream tarInput = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream("c://temp//test.tar.gz")));
TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
while (currentEntry != null) {
    File f = currentEntry.getFile();
    br = new BufferedReader(new FileReader(f));
    System.out.println("For File = " + currentEntry.getName());
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println("line="+line);
    }
}
if (br!=null) {
    br.close();
}

But I get null when I call the getFile method of TarArchiveEntry.
I am using Apache commons compress 1.8.1

4

1 回答 1

24

不能使用 TarArchiveEntry 的 getFile。当您在 tar 文件中压缩文件时,该 getter 仅用于相反的操作。

相反,您应该直接从 TarArchiveInputStream 中读取。它将负责将“文件”的内容返回给您,并即时解压缩它。

例如(未经测试的代码,YMMV):

TarArchiveInputStream tarInput = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream("c://temp//test.tar.gz")));
TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
while (currentEntry != null) {
    br = new BufferedReader(new InputStreamReader(tarInput)); // Read directly from tarInput
    System.out.println("For File = " + currentEntry.getName());
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println("line="+line);
    }
    currentEntry = tarInput.getNextTarEntry(); // You forgot to iterate to the next file
}
于 2014-09-09T16:33:13.077 回答