0

我有一个学校作业,要求我使用 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;
}
4

1 回答 1

0

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

使用时的正常调用顺序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")异常所说的。

您还可以阅读文档中的示例。这解释了(例如)7z 的归档器具有不同的超类。

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


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

于 2019-03-12T13:17:49.923 回答