From c6dbdeaaa5ecffef4bf18828a44d604255d9703e Mon Sep 17 00:00:00 2001 From: vunamtien Date: Tue, 14 Nov 2023 18:41:43 +0700 Subject: [PATCH] BAEL-7106-compress-and-uncompress-bytes (#15216) --- .../compressbytes/CompressByteArrayUtil.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java new file mode 100644 index 0000000000..88e2283985 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java @@ -0,0 +1,58 @@ +package com.baeldung.compressbytes; + +import java.io.ByteArrayOutputStream; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +public class CompressByteArrayUtil { + + public static byte[] compress(byte[] input) { + Deflater deflater = new Deflater(); + deflater.setInput(input); + deflater.finish(); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + + while (!deflater.finished()) { + int compressedSize = deflater.deflate(buffer); + outputStream.write(buffer, 0, compressedSize); + } + + return outputStream.toByteArray(); + } + + public static byte[] decompress(byte[] input) throws DataFormatException { + Inflater inflater = new Inflater(); + inflater.setInput(input); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + + while (!inflater.finished()) { + int decompressedSize = inflater.inflate(buffer); + outputStream.write(buffer, 0, decompressedSize); + } + + return outputStream.toByteArray(); + } + + public static void main(String[] args) throws Exception { + String inputString = "Baeldung helps developers explore the Java ecosystem and simply be better engineers. " + + "We publish to-the-point guides and courses, with a strong focus on building web applications, Spring, " + + "Spring Security, and RESTful APIs"; + byte[] input = inputString.getBytes(); + + // Compression + byte[] compressedData = compress(input); + + // Decompression + byte[] decompressedData = decompress(compressedData); + + System.out.println("Original: " + input.length + " bytes"); + System.out.println("Compressed: " + compressedData.length + " bytes"); + System.out.println("Decompressed: " + decompressedData.length + " bytes"); + } + +}