import java.nio.charset.StandardCharsets; import java.util.zip.Deflater; public class DeflaterSmallBufferBug { public static void main(String[] args) { boolean nowrap = true; Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION,nowrap); byte[] input = "Hello".getBytes(StandardCharsets.UTF_8); System.out.printf("input is %,d bytes - %s%n",input.length,getHex(input,0,input.length)); deflater.setInput(input); byte[] output = new byte[input.length]; // break out of infinite loop seen with bug int maxloops = 10; // Compress the data while (maxloops-- > 0) { int compressed = deflater.deflate(output,0,output.length,Deflater.SYNC_FLUSH); System.out.printf("compressed %,d bytes - %s%n",compressed,getHex(output,0,compressed)); if (compressed < output.length) { System.out.printf("Compress success"); return; } } System.out.printf("Exited compress (maxloops left %d)%n",maxloops); } private static String getHex(byte[] buf, int offset, int len) { StringBuilder hex = new StringBuilder(); hex.append('['); for (int i = offset; i < (offset + len); i++) { if (i > offset) { hex.append(' '); } hex.append(String.format("%02X",buf[i])); } hex.append(']'); return hex.toString(); } }