[BAEL-7659] Compress and Create a Byte Array Using GZip (#16451)

* [BAEL-7659] Compress and create a byte array using GZip

* [BAEL-7659] Compress and Create a Byte Array Using GZip

* [BAEL-7659] Compress and Create a Byte Array Using GZip

* [BAEL-7659] Compress and Create a Byte Array Using GZip

* [BAEL-7659] Compress and create a byte array using GZip

---------

Co-authored-by: p.kostopoulos <p.kostopoulos@astynomia.gr>
This commit is contained in:
8122171911 2024-04-20 17:03:22 +03:00 committed by GitHub
parent 7163e8b266
commit 9e0ad0a0c7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 52 additions and 0 deletions

View File

@ -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();
}
}

View File

@ -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));
}
}