如何将 ArchiveEntry 转换为 InputStream?

mem*_*und 7 java apache-commons-compress

我正在阅读tar.gz档案使用

ArchiveEntry entry = tarArchiveInputStream.getNextEntry();

问题:如何将此ArchiveEntry转换为 ,InputStream以便我可以实际读取文件并将其处理为String

小智 4

您可以使用 IOUtils 来完整读取 InputStream:

import org.apache.commons.compress.utils.IOUtils

byte[] buf = new byte[(int) entry.getSize()];
int readed  = IOUtils.readFully(tarArchiveInputStream,buf);

//readed should equal buffer size
if(readed != buf.length) {
 throw new RuntimeException("Read bytes count and entry size differ");
}

String string = new String(buf, StandardCharsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)

如果您的文件采用 utf-8 以外的其他编码,请在 string 的构造函数中使用它而不是 utf-8。