Search code examples
javagzipjava-7flush

Is it safe to flush a GZIPOutputStream followed by a ByteArrayOutputStream reset?


Here is an example code

ByteArrayOutputStream baos = new ByteArrayOutputStream(bufSize);
GZIPOutputStream gzos = new GZIPOutputStream1(baos);
gzos.write(...)
...
gzos.write(...)
...
// Would the content get flushed properly?
gzos.flush()
byte[] bytes =  baos.toByteArray();
// Use bytes wherever you want
...
// Would this reset things for gzos?
baos.reset()
gzos.write(...)
...
gzos.write(...)
...
bytes =  baos.toByteArray();
...

So, once the compressed byte array is used somewhere, I want to reset the stream. I have two concerns. I read somewhere that GZIPOutputStream's flush method do not necessarily always flushes the content? Is that true still for Java 7? If that works, is calling reset of the ByteArrayOutputStream object enough to reset things for the GZIPOutputStream object?


Solution

  • I read somewhere that GZIPOutputStream's flush method do not necessarily always flushes the content?

    It depends on what GZIPOutputStream constructor you use. If you create a compressor passing true to boolean syncFlush, any flush() call will flush both compressor and output stream, respectively. If false, only the output strem will flush.

    Is that true still for Java 7?

    The behavior you described happened in Java 6. This syncFlush parameter is available since Java 7. It' in Java 8, of course.

    If that works, is calling reset of the ByteArrayOutputStream object enough to reset things for the GZIPOutputStream object?

    Yes, it seems so.