责备历史先例。在Unix上,用于反转a的函数deflate
称为inflate
。因此,与许多其他Java IO类不同,输入和输出流对不具有(显然)匹配的名称。
实际上,DeflaterOutputStream不允许您逆转通缩,而是在将字节从接收器传递到源时,对字节进行放气。DeflaterInputStream也可以 放气,但是它在数据从源流向接收器时执行其操作。
为了读取未压缩(膨胀)格式的数据,您需要使用InflaterInputStream
:
InflaterInputStream inputStream = new InflaterInputStream(arrayInputStream);
另外,由于可能无法在一个read
调用中从流中获取所有压缩数据,因此需要使用循环。像这样:
int read;
byte[] finalBuf = new byte[0], swapBuf;
byte[] readBuffer = new byte[5012];
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(
compressed);
InflaterInputStream inputStream = new InflaterInputStream(
arrayInputStream);
while ((read = inputStream.read(readBuffer)) != -1) {
System.out.println("Intermediate read: " + read);
swapBuf = finalBuf;
finalBuf = new byte[swapBuf.length + read];
System.arraycopy(swapBuf, 0, finalBuf, 0, swapBuf.length);
System.arraycopy(readBuffer, 0, finalBuf, swapBuf.length, read);
}