Deflater And Inflater Roundtrip
Compress payloads with Deflater and restore them with Inflater, checking byte counts, zlib headers, and a lossless round trip.
Code
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class DeflateRoundtrip {
public static void main(String[] args) throws Exception {
byte[] original = ("{\"topic\":\"deflate\",\"repeat\":\""
+ "payload-".repeat(12) + "\"}")
.getBytes(StandardCharsets.UTF_8);
// Deflater:BEST_COMPRESSION 提高压缩比,输出带 zlib 包装
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
deflater.setInput(original);
deflater.finish();
byte[] buffer = new byte[1024];
int compressedSize = deflater.deflate(buffer);
deflater.end();
System.out.println("original bytes: " + original.length);
System.out.println("compressed bytes: " + compressedSize);
System.out.println("zlib header: " + String.format("%02x %02x", buffer[0], buffer[1]));
// Inflater:输入长度必须与压缩时一致
Inflater inflater = new Inflater();
inflater.setInput(buffer, 0, compressedSize);
byte[] restored = new byte[original.length];
int restoredSize = inflater.inflate(restored);
inflater.end();
System.out.println("restored bytes: " + restoredSize);
System.out.println("roundtrip equal: " + Arrays.equals(original, restored));
}
}How the snippet works
Deflater And Inflater Roundtrip keeps everything in the class DeflateRoundtrip.
Applying it
The demo output is labeled (original bytes:, compressed bytes:, zlib header:), so every printed line maps back to its originating operation.
Statements that matter
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
int compressedSize = deflater.deflate(buffer);
int restoredSize = inflater.inflate(restored);
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Deflater And Inflater Roundtrip print when run?
- The script runs standalone; its 5 labeled outputs include `original bytes:`, `compressed bytes:`, `zlib header:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.