使用Commons-compression读取Java中的tar.gz [英] Read tar.gz in Java with Commons-compression
问题描述
好,所以我想读取tar.gz文件(或xy)的内容,但这是同一回事. 我正在做的或多或少是这样的:
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();
}
但是当我调用TarArchiveEntry
的getFile
方法时,我得到的是null.
我正在使用Apache Commons compress 1.8.1
But I get null when I call the getFile
method of TarArchiveEntry
.
I am using Apache commons compress 1.8.1
推荐答案
您不能使用TarArchiveEntry的getFile.当您压缩tar文件中的文件时,该吸气剂仅用于相反的操作.
You can't use the getFile of TarArchiveEntry. That getter is there only for the opposite operation, when you are compressing files inside a tar file.
相反,您应该直接从TarArchiveInputStream阅读.它将负责向您返回动态解压缩的文件"内容.
Instead, you should read directly from TarArchiveInputStream. It will take care of returning you the content of the "file" decompressing it on the fly.
例如(未经测试的代码,YMMV):
For example (untested code, 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
}
这篇关于使用Commons-compression读取Java中的tar.gz的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!