【问题标题】:Compressing InputStream using apache commons compress library使用 apache commons compress library 压缩 InputStream
【发布时间】:2019-03-12 13:04:20
【问题描述】:

我有一个学校作业,要求我使用 apache commons compress library 接收输入流并将其压缩为具有 5 种格式之一的字节数组(根据用户规范)。 5 种格式是:ZIP、JAR、SEVENZ、BZIP2 和 GZIP。我编写了以下方法来压缩 JAR 格式的输入流,但得到了一个非法状态异常,字符串为“No current entry”。

private byte[] documentJARCompression(InputStream in) throws IOException {
    BufferedInputStream buffIn = new BufferedInputStream(in);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JarArchiveOutputStream jarOut = new JarArchiveOutputStream(out);
    final byte[] buffer = new byte[out.size()];
    int n = 0;
    while (-1 != (n = buffIn.read(buffer))) {
        jarOut.write(buffer, 0, n);
    }
    jarOut.close();
    return buffer;
}

【问题讨论】:

  • Jar == Zip 是多文件压缩,其中每个文件都是一个带有文件名的条目。
  • 你看tutorial了吗?

标签: java apache-commons-compress


【解决方案1】:

您需要阅读您正在使用的 Apache 类的 javadocs ... 及其超类。例如,ArchiveOutputStream(jar 和 zip 归档器类的超类型)的 javadoc 表示:

使用ArchiveOutputStreams 时的正常调用顺序 是:

Create ArchiveOutputStream object,
optionally write SFX header (Zip only),
repeat as needed:
    putArchiveEntry(ArchiveEntry) (writes entry header),
    OutputStream.write(byte[]) (writes entry data, as often as needed),
    closeArchiveEntry() (closes entry), 
finish() (ends the addition of entries),
optionally write additional data, provided format supports it,
OutputStream.close().

您直接启动了write 调用,而没有向归档程序提供有关您要添加到 JAR 文件中的条目所需的信息。这就是IllegalStateException("No current entry") 异常的意思。

您还可以阅读文档中的examples。这说明(例如)7z 的存档器具有不同的超类。

请注意,zip、jar 和 7z 文件并不是简单的压缩格式。它们是用于将多个文件打包到一个存档中的存档格式。


简而言之,您应该在尝试使用 API 之前阅读它的文档。

【讨论】:

    猜你喜欢
    • 2013-01-04
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2015-03-25
    相关资源
    最近更新 更多