Java.Streams.Which classes support reading and writing streams in compressed format?

Great one, Stanley! 😎 In Java, working with compressed streams (like ZIP or GZIP) is well-supported — especially for reading/writing data on-the-fly in a compressed format.

Here are the key classes you’ll want to know:


🗜️ Classes for Reading/Writing Compressed Streams

ClassPackagePurpose
GZIPInputStreamjava.util.zipReads data from a GZIP-compressed input stream
GZIPOutputStreamjava.util.zipWrites data to a stream in GZIP format
ZipInputStreamjava.util.zipReads ZIP archive entries sequentially
ZipOutputStreamjava.util.zipWrites ZIP archive entries
InflaterInputStreamjava.util.zipReads data compressed with DEFLATE
DeflaterOutputStreamjava.util.zipWrites data in DEFLATE format
JarInputStreamjava.util.jarReads JAR files (which are ZIP + manifest)
JarOutputStreamjava.util.jarWrites JAR files

✅ GZIP Example

import java.io.*;
import java.util.zip.*;

public class GzipExample {
    public static void main(String[] args) throws IOException {
        // Compress
        try (FileOutputStream fos = new FileOutputStream("data.gz");
             GZIPOutputStream gzipOut = new GZIPOutputStream(fos);
             OutputStreamWriter writer = new OutputStreamWriter(gzipOut)) {
            writer.write("Hello, compressed world!");
        }

        // Decompress
        try (FileInputStream fis = new FileInputStream("data.gz");
             GZIPInputStream gzipIn = new GZIPInputStream(fis);
             InputStreamReader reader = new InputStreamReader(gzipIn);
             BufferedReader br = new BufferedReader(reader)) {
            System.out.println("Decompressed: " + br.readLine());
        }
    }
}

✅ ZIP Example (Multiple Entries)

try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("archive.zip"))) {
    ZipEntry entry = new ZipEntry("hello.txt");
    zos.putNextEntry(entry);
    zos.write("Hello from ZIP!".getBytes());
    zos.closeEntry();
}

🧵 TL;DR

FormatFor ReadingFor Writing
GZIPGZIPInputStreamGZIPOutputStream
ZIPZipInputStream, JarInputStreamZipOutputStream, JarOutputStream
DEFLATEInflaterInputStreamDeflaterOutputStream

These classes wrap around InputStream/OutputStream, so you can use them in stream chains like with BufferedReader, PrintWriter, etc.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.