使用Commons-compression读取Java中的tar.gz

前端之家收集整理的这篇文章主要介绍了使用Commons-compression读取Java中的tar.gz前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好的,我想阅读tar.gz文件(或xy)的内容,但这是一回事.
我正在做的或多或少是这样的:
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();
}

但是当我调用TarArchiveEntry的getFile方法时,我得到null.
我正在使用Apache commons compress 1.8.1

解决方法

您不能使用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
}
原文链接:https://www.f2er.com/java/127793.html

猜你在找的Java相关文章