membersound membersound - 1 month ago 12
Java Question

How to convert ArchiveEntry to InputStream?

I'm reading a

tar.gz
archive using

ArchiveEntry entry = tarArchiveInputStream.getNextEntry();


Question: how can I convert this ArchiveEntry to an
InputStream
so I can actually read and process the file to a
String
?

Answer Source

You could use IOUtils to read InputStream fully:

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);

If your file is in other encoding than utf-8, use that instead of utf-8 in the constructor of string.