GZIP Compression and Decompression using Java

Hi, I'm Srivastava, in this post we will see how to compress and decompress data using GZIP in Java.
The java.util.zip package provides classes that compress and decompress the file contents. GZIPOutputStream
and GZIPInputStream
classes are provided in Java to compress and decompress the files. We will make use of methods write()
to compress and read()
to decompress.
Here is the complete code to compress and decompress string data and file.
import lombok.NonNull;
import org.jetbrains.annotations.Contract;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPUtils {
public static byte[] compress(final String data) {
if (data == null || data.length() == 0) {
return null;
}
try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
gzipOutputStream.write(data.getBytes(StandardCharsets.UTF_8));
gzipOutputStream.finish();
gzipOutputStream.flush();
gzipOutputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (final IOException e) {
throw new UncheckedIOException("Error while compression", e);
}
}
@Contract(pure = true)
public static @NonNull String decompress(final byte[] data) {
final StringBuilder stringBuilder = new StringBuilder();
if (data == null || data.length == 0) {
return "";
}
if (isCompressed(data)) {
try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(data))) {
final byte[] buffer = new byte[1024];
int length;
while ((length = gzipInput.read(buffer)) >= 0) {
stringBuilder.append(new String(buffer, 0, length, StandardCharsets.UTF_8));
}
} catch (IOException e) {
throw new UncheckedIOException("Error while decompression!", e);
}
} else {
stringBuilder.append(Arrays.toString(data));
}
return stringBuilder.toString();
}
public static void compressFile(File inFile, File outFile) throws IOException {
try (final InputStream in = new FileInputStream(inFile);
final OutputStream out = new GZIPOutputStream(new FileOutputStream(outFile))) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
}
public static void decompressFile(File inFile, File outFile) throws IOException {
try (final InputStream in = new GZIPInputStream(new FileInputStream(inFile));
final OutputStream out = new FileOutputStream(outFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
}
@Contract(pure = true)
private static boolean isCompressed(final byte @NonNull [] compressed) {
return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) &&
(compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}
}