I am trying to bzip2 data in memory using commons compress. I am trying this:
private static final int bufferSize = 8192;
public void compress(
ByteArrayInputStream byteArrayInputStream,
CompressorOutputStream compressorOutputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final byte[] buffer = new byte[bufferSize];
int n = 0;
while (-1 != (n = byteArrayInputStream.read(buffer)))
compressorOutputStream.write(buffer, 0, n);
}
public byte[] compressBZIP2(byte[] inputBytes) throws Exception {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(inputBytes);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BZip2CompressorOutputStream bZip2CompressorOutputStream = new BZip2CompressorOutputStream(byteArrayOutputStream);
compress(byteArrayInputStream, bZip2CompressorOutputStream);
return byteArrayOutputStream.toByteArray();
}
But this doesnt work:
byte[] bzipCompressed = resultCompressor.compressBZIP2(contentBytes);
The result always has 3 bytes, and that's all.
What am I doing wrong?
You never close the
BZip2CompressorOutputStream
which means the final (and likely only) block of data will never get written to the wrapped stream.