javaapache-commons-compress

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?


Solution

  • 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.