编程语言
首页 > 编程语言> > java-如何刷新DeflatorOutputStream中的缓冲数据

java-如何刷新DeflatorOutputStream中的缓冲数据

作者:互联网

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

解决方法:

我应该阅读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.

标签:flush,deflate,java
来源: https://codeday.me/bug/20191122/2062415.html