【问题标题】:How to convert ArchiveEntry to InputStream?如何将 ArchiveEntry 转换为 InputStream?
【发布时间】:2016-04-11 18:09:05
【问题描述】:

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

ArchiveEntry entry = tarArchiveInputStream.getNextEntry();

问题:如何将这个ArchiveEntry 转换为InputStream,这样我才能真正读取文件并将其处理为String

【问题讨论】:

  • 澄清一下,您的意思是来自 Apache 的 commons-compress 的 org.apache.commons.compress.archivers.ArchiveEntry
  • 是的,我的意思是 commons.compress。

标签: java apache-commons-compress


【解决方案1】:

您可以使用 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);

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

【讨论】:

  • 这可能是正确的解决方案,因为IOUtils.readFully 可以直接从commons.compress 使用。
【解决方案2】:

已经是InputStream

byte[] buf = new byte[(int) entry.getSize()];
int k = tarArchiveInputStream.read(buf, 0, buf.length);
String s = new String(buf, 0, k);

【讨论】:

    【解决方案3】:

    如果你真的要一个一个的读取文件,TarEntry其实就是把File对象保存在里面的:

    此类表示 Tar 存档中的条目。它由条目的标题和条目的文件组成。

    因此只需初始化另一个 FileInputStream 就足够了:

    import org.apache.commons.io.IOUtils;
    String file = IOUtils.toString(new FileInputStream(entry.getFile());
    

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 2011-12-12
      • 2011-02-19
      • 2013-06-11
      • 2020-02-27
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多