java
28 lines · 6 steps
Compressing byte arrays with GZIP in Java
A small utility that round-trips byte arrays through GZIP streams using try-with-resources for safe flushing.
Explained by
highlit
1import java.io.ByteArrayInputStream;
2import java.io.ByteArrayOutputStream;
3import java.io.IOException;
4import java.util.zip.GZIPInputStream;
5import java.util.zip.GZIPOutputStream;
6
7public final class GzipCodec {
8
9 public static byte[] compress(byte[] data) throws IOException {
10 ByteArrayOutputStream buffer = new ByteArrayOutputStream(Math.max(64, data.length / 2));
11 try (GZIPOutputStream gzip = new GZIPOutputStream(buffer)) {
12 gzip.write(data);
13 }
14 return buffer.toByteArray();
15 }
16
17 public static byte[] decompress(byte[] compressed) throws IOException {
18 ByteArrayOutputStream buffer = new ByteArrayOutputStream(compressed.length * 2);
19 try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
20 byte[] chunk = new byte[8192];
21 int read;
22 while ((read = gzip.read(chunk)) != -1) {
23 buffer.write(chunk, 0, read);
24 }
25 }
26 return buffer.toByteArray();
27 }
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping a GZIPOutputStream in try-with-resources guarantees the trailer is written when the block closes.
- 2In-memory streams let you convert compression stream APIs into simple byte-array-in, byte-array-out functions.
- 3Reading through a fixed buffer in a loop handles output of unknown size without allocating for the whole result up front.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/compressing-byte-arrays-with-gzip-in-java-explained-java-47aa/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.