我希望能够刷新 DeflaterOutputStream 中的任何待处理数据并在 InflaterInputStream 中读取它。但是,flush() 似乎并没有这样做。还有其他方法吗?
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(baos);
for(char ch = 'a';ch <= 'z';ch ++) {
dos.write(ch);
dos.flush();
System.out.println("compressed size = "+baos.toByteArray().length);
}
dos.close();
System.out.println("After close, compressed size = "+baos.toByteArray().length);
我期望看到的是每次刷新时大小都会增加,因为它会刷新任何挂起/缓冲的数据。然而,事实并非如此。它只是停留在缓冲区中,直到我关闭流。
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
compressed size = 2
After close, compressed size = 34
如果 DeflaterOutputStream 不支持这一点,是否有压缩流支持?
我查看了 Apache Commons Compress,唯一刷新数据的流是 XZCompressorInputStream,但这样做,数据比不压缩大 50%。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
XZCompressorOutputStream dos = new XZCompressorOutputStream(baos);
for (char ch = 'a'; ch <= 'z'; ch++) {
dos.write(("Hello world").getBytes());
baos2.write(("Hello world").getBytes());
dos.flush();
System.out.println("compressed size = " + baos.toByteArray().length);
}
dos.close();
System.out.println("After close, compressed size = " + baos.toByteArray().length);
System.out.println("uncompressed size = " + baos2.toByteArray().length);
最后打印
compressed size = 388
After close, compressed size = 424
uncompressed size = 286