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

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

解决方案

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.

Instead, you should read directly from TarArchiveInputStream. It will take care of returning you the content of the "file" decompressing it on the fly.

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

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值