import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
import java.util.zip.InflaterOutputStream;

public class DiffInflaterStream {
    public static void main(String[] args) throws IOException {
        byte[] input = "Hello, World!".getBytes(StandardCharsets.UTF_8);
        Deflater def = new Deflater();
        def.setInput(input);
        //def.finish(); // <--- uncomment this line to fix the issue
        byte[] buffer = new byte[100];
        int compressedDataLength = def.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH); // <--- only occurs with Deflater.SYNC_FLUSH and without def.finish()
        byte[] compressedData = new byte[compressedDataLength];
        System.arraycopy(buffer, 0, compressedData, 0, compressedDataLength);
        def.end();

        // Decompress using InflaterOutputStream
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(byteArrayOutputStream)) {
            inflaterOutputStream.write(compressedData);
            System.out.println("InflaterOutputStream: " + new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

        // Decompress using InflaterInputStream
        try (InflaterInputStream inflaterInputStream = new InflaterInputStream(new ByteArrayInputStream(compressedData))) {
            System.out.println("InflaterInputStream: " + new String(inflaterInputStream.readAllBytes(), StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

        // Why InflaterInputStream throws an exception and InflaterOutputStream doesn't?
    }
}