diff --git a/core-java-modules/core-java-io-5/src/main/java/com/baeldung/gzipbytearray/GZip.java b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/gzipbytearray/GZip.java new file mode 100644 index 0000000000..bbe43bbb60 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/gzipbytearray/GZip.java @@ -0,0 +1,22 @@ +package com.baeldung.gzipbytearray; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.zip.GZIPOutputStream; + +public class GZip { + + private static final int BUFFER_SIZE = 512; + + public static void gzip(InputStream is, OutputStream os) throws IOException { + GZIPOutputStream gzipOs = new GZIPOutputStream(os); + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = 0; + while ((bytesRead = is.read(buffer)) > -1) { + gzipOs.write(buffer, 0, bytesRead); + } + gzipOs.close(); + } + +} diff --git a/core-java-modules/core-java-io-5/src/test/java/com/baeldung/gzipbytearray/GZipUnitTest.java b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/gzipbytearray/GZipUnitTest.java new file mode 100644 index 0000000000..09db1bbe73 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/gzipbytearray/GZipUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.gzipbytearray; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GZipUnitTest { + + Logger logger = LoggerFactory.getLogger(GZipUnitTest.class); + + @Test + void whenCompressingUsingGZip_thenGetCompressedByteArray() throws IOException { + String payload = "This is a sample text to test method gzip. The gzip algorithm will compress this string. " + + "The result will be smaller than this string."; + ByteArrayOutputStream os = new ByteArrayOutputStream(); + GZip.gzip(new ByteArrayInputStream(payload.getBytes()), os); + byte[] compressed = os.toByteArray(); + assertTrue(payload.getBytes().length > compressed.length); + assertEquals("1f", Integer.toHexString(compressed[0] & 0xFF)); + assertEquals("8b", Integer.toHexString(compressed[1] & 0xFF)); + } + +}