0

I have a school assignment that requires my to take in an inputstream and compress it into a byte array with one of 5 formats (by the user specification) using the apache commons compress library. The 5 formats are: ZIP, JAR, SEVENZ, BZIP2 and GZIP. I wrote the following method to compress the input stream with the JAR format but am getting an illegalStateException with the string "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;
}

1 Answers1

0

You need to read the javadocs for the Apache classes that you are using ... and its superclasses. For example, the javadoc for ArchiveOutputStream (a supertype for the jar and zip archiver classes) says this:

The normal sequence of calls when working with ArchiveOutputStreams is:

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().

You have launched straight into a write call without giving the archiver the information it needs about the entry you are adding to the JAR file. That is what the IllegalStateException("No current entry") exception is saying.

You could also read the examples in the documentation. This explain (for example) that the archiver for 7z has a different superclass.

Note that zip, jar and 7z files are not simply compression formats. They are archive formats for packing multiple files into a single archive.


In short, you should read an API's documentation before you try to use it.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216