I should have read the Javadoc. There is an option to the constructor syncFlush
and if true gives the behaviour I want.
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);
prints finally
compressed size = 212
compressed size = 220
After close, compressed size = 226
uncompressed size = 286
Note: this was only added in Java 7, and I was looking at Java 6.