3

我希望能够刷新 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
4

1 回答 1

3

我应该阅读 Javadoc。构造函数有一个选项syncFlush,如果 true 给出了我想要的行为。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(baos, true);

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 = 212
compressed size = 220
After close, compressed size = 226
uncompressed size = 286

注意:这只是在 Java 7 中添加的,我正在查看 Java 6。

于 2013-09-12T13:08:45.220 回答